aboutsummaryrefslogtreecommitdiffstats
path: root/apps/mobile/lib/settings.ts
diff options
context:
space:
mode:
Diffstat (limited to 'apps/mobile/lib/settings.ts')
-rw-r--r--apps/mobile/lib/settings.ts51
1 files changed, 34 insertions, 17 deletions
diff --git a/apps/mobile/lib/settings.ts b/apps/mobile/lib/settings.ts
index 13de067e..3ec53231 100644
--- a/apps/mobile/lib/settings.ts
+++ b/apps/mobile/lib/settings.ts
@@ -1,6 +1,5 @@
import * as SecureStore from "expo-secure-store";
-
-import { useStorageState } from "./storage-state";
+import { create } from "zustand";
const SETTING_NAME = "settings";
@@ -9,22 +8,40 @@ export interface Settings {
address: string;
}
-export default function useAppSettings() {
- const [settingsState, setSettings] = useStorageState<Settings>(SETTING_NAME);
- const [isLoading] = settingsState;
- let [, settings] = settingsState;
+interface AppSettingsState {
+ settings: { isLoading: boolean; settings: Settings };
+ setSettings: (settings: Settings) => Promise<void>;
+ load: () => Promise<void>;
+}
- settings ||= {
- address: "https://demo.hoarder.app",
- };
+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 } }));
+ },
+}));
- return { settings, setSettings, isLoading };
-}
+export default function useAppSettings() {
+ const { settings, setSettings, load } = useSettings();
-export async function getAppSettings() {
- const val = await SecureStore.getItemAsync(SETTING_NAME);
- if (!val) {
- return null;
- }
- return JSON.parse(val) as Settings;
+ return { ...settings, setSettings, load };
}