aboutsummaryrefslogtreecommitdiffstats
path: root/apps/mobile/lib/storage-state.ts
diff options
context:
space:
mode:
authorMohamedBassem <me@mbassem.com>2024-03-13 21:43:44 +0000
committerMohamed Bassem <me@mbassem.com>2024-03-14 16:40:45 +0000
commit04572a8e5081b1e4871e273cde9dbaaa44c52fe0 (patch)
tree8e993acb732a50d1306d4d6953df96c165c57f57 /apps/mobile/lib/storage-state.ts
parent2df08ed08c065e8b91bc8df0266bd4bcbb062be4 (diff)
downloadkarakeep-04572a8e5081b1e4871e273cde9dbaaa44c52fe0.tar.zst
structure: Create apps dir and copy tooling dir from t3-turbo repo
Diffstat (limited to 'apps/mobile/lib/storage-state.ts')
-rw-r--r--apps/mobile/lib/storage-state.ts51
1 files changed, 51 insertions, 0 deletions
diff --git a/apps/mobile/lib/storage-state.ts b/apps/mobile/lib/storage-state.ts
new file mode 100644
index 00000000..4988f0e0
--- /dev/null
+++ b/apps/mobile/lib/storage-state.ts
@@ -0,0 +1,51 @@
+import * as SecureStore from "expo-secure-store";
+import * as React from "react";
+
+type UseStateHook<T> = [[boolean, T | null], (value: T | null) => void];
+
+function useAsyncState<T>(
+ initialValue: [boolean, T | null] = [true, null],
+): UseStateHook<T> {
+ return React.useReducer(
+ (
+ state: [boolean, T | null],
+ action: T | null = null,
+ ): [boolean, T | null] => [false, action],
+ initialValue,
+ ) as UseStateHook<T>;
+}
+
+export async function setStorageItemAsync(key: string, value: string | null) {
+ if (value == null) {
+ await SecureStore.deleteItemAsync(key);
+ } else {
+ await SecureStore.setItemAsync(key, value);
+ }
+}
+
+export function useStorageState<T>(key: string): UseStateHook<T> {
+ // Public
+ const [state, setState] = useAsyncState<T>();
+
+ // Get
+ React.useEffect(() => {
+ SecureStore.getItemAsync(key).then((value) => {
+ if (!value) {
+ setState(null);
+ return null;
+ }
+ setState(JSON.parse(value));
+ });
+ }, [key]);
+
+ // Set
+ const setValue = React.useCallback(
+ (value: T | null) => {
+ setState(value);
+ setStorageItemAsync(key, JSON.stringify(value));
+ },
+ [key],
+ );
+
+ return [state, setValue];
+}