-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSQLiteTable.ts
More file actions
48 lines (41 loc) · 1.27 KB
/
useSQLiteTable.ts
File metadata and controls
48 lines (41 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { isEqual } from 'es-toolkit';
import { useEffect, useMemo, useState } from 'react';
import { SQLiteTable } from './SQLiteTable/core/SQLiteTable';
import type { ColumnMapInput, DDLOption } from './SQLiteTable/types';
type UseSQLiteTableOptions<T extends Record<string, unknown>> = {
dbName?: string;
tableName: string;
columns: ColumnMapInput<T>;
ddlOption?: DDLOption;
};
export const useSQLiteTable = <T extends Record<string, unknown>>({
dbName,
tableName,
columns,
ddlOption,
}: UseSQLiteTableOptions<T>) => {
const [stableCols, setStableCols] = useState<ColumnMapInput<T>>(columns);
const [stableDDLOption, setStableDDLOption] = useState<DDLOption | undefined>(ddlOption);
useEffect(() => {
if (!isEqual(columns, stableCols)) setStableCols(columns);
if (!isEqual(ddlOption, stableDDLOption)) setStableDDLOption(ddlOption);
}, [columns, stableCols, ddlOption, stableDDLOption]);
const table = useMemo(
() =>
new SQLiteTable<T>(
dbName ?? 'MyAppSQLiteDB',
tableName,
stableCols,
stableDDLOption,
true,
),
[dbName, tableName, stableCols, stableDDLOption],
);
useEffect(() => {
void table.open();
return () => {
void table.close();
};
}, [table]);
return table;
};