-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDictionaryContext.tsx
66 lines (55 loc) · 1.63 KB
/
DictionaryContext.tsx
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import {
createContext,
useContext,
useEffect,
useState,
ReactNode,
} from "react";
import * as SQLite from "expo-sqlite";
import Storage from "expo-sqlite/kv-store";
import { DB_DICTIONARY_KEY, Dictionary } from "../constants/database";
interface DictionaryContextType {
currentDictionary: Dictionary;
setDictionary: (dictionary: Dictionary) => void;
}
const DictionaryContext = createContext<DictionaryContextType | undefined>(
undefined,
);
export function DictionaryProvider({ children }: { children: ReactNode }) {
const [currentDictionary, setCurrentDictionary] = useState<Dictionary>(
Dictionary.NWL2023,
);
useEffect(() => {
const storedDictionary = Storage.getItemSync(DB_DICTIONARY_KEY);
const dictionaryToUse = storedDictionary
? (storedDictionary as Dictionary)
: Dictionary.NWL2023;
setCurrentDictionary(dictionaryToUse);
}, []);
function setDictionary(dictionary: Dictionary) {
Storage.setItemSync(DB_DICTIONARY_KEY, dictionary);
// Close existing database connection
const oldDb = SQLite.openDatabaseSync(`${currentDictionary}.db`);
oldDb.closeSync();
// Open new database connection
SQLite.openDatabaseSync(`${dictionary}.db`);
setCurrentDictionary(dictionary);
}
return (
<DictionaryContext.Provider
value={{
currentDictionary,
setDictionary,
}}
>
{children}
</DictionaryContext.Provider>
);
}
export function useDictionary() {
const context = useContext(DictionaryContext);
if (context === undefined) {
throw new Error("useDictionary must be used within a DictionaryProvider");
}
return context;
}