From 2cd2f92e9e0c82eaa5f21fe0c30e20ebea7aba24 Mon Sep 17 00:00:00 2001 From: MohamedBassem Date: Fri, 22 Mar 2024 15:10:24 +0000 Subject: fix(mobile): Fix setting propagatin --- apps/mobile/lib/settings.ts | 51 ++++++++++++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 17 deletions(-) (limited to 'apps/mobile/lib/settings.ts') 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(SETTING_NAME); - const [isLoading] = settingsState; - let [, settings] = settingsState; +interface AppSettingsState { + settings: { isLoading: boolean; settings: Settings }; + setSettings: (settings: Settings) => Promise; + load: () => Promise; +} - settings ||= { - address: "https://demo.hoarder.app", - }; +const useSettings = create((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 }; } -- cgit v1.2.3-70-g09d2