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 * as SecureStore from "expo-secure-store";
import { create } from "zustand";
const SETTING_NAME = "settings";
export interface Settings {
apiKey?: string;
apiKeyId?: string;
address: string;
}
interface AppSettingsState {
settings: { isLoading: boolean; settings: Settings };
setSettings: (settings: Settings) => Promise<void>;
load: () => Promise<void>;
}
const useSettings = create<AppSettingsState>((set, get) => ({
settings: {
isLoading: true,
settings: { address: "" },
},
setSettings: async (settings) => {
await SecureStore.setItemAsync(SETTING_NAME, JSON.stringify(settings));
set((_state) => ({ settings: { isLoading: false, settings } }));
},
load: async () => {
if (!get().settings.isLoading) {
return;
}
const strVal = await SecureStore.getItemAsync(SETTING_NAME);
if (!strVal) {
set((state) => ({
settings: { isLoading: false, settings: state.settings.settings },
}));
return;
}
// TODO Wipe the state if invalid
const parsed = JSON.parse(strVal) as Settings;
set((_state) => ({ settings: { isLoading: false, settings: parsed } }));
},
}));
export default function useAppSettings() {
const { settings, setSettings, load } = useSettings();
return { ...settings, setSettings, load };
}
|