Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useLocalStorage.ts

143 lines4.5 KB

1import * as Schema from "effect/Schema";
2import * as Record from "effect/Record";
3import { useCallback, useEffect, useRef, useState } from "react";
4​
5const isomorphicLocalStorage: Storage =
6 typeof window !== "undefined"
7 ? window.localStorage
8 : (function () {
9 const store = new Map<string, string>();
10 return {
11 clear: () => store.clear(),
12 getItem: (_) => store.get(_) ?? null,
13 key: (_) => Record.keys(store).at(_) ?? null,
14 get length() {
15 return store.size;
16 },
17 removeItem: (_) => store.delete(_),
18 setItem: (_, value) => store.set(_, value),
19 };
20 })();
21​
22const decode = <T, E>(schema: Schema.Codec<T, E>, value: string) =>
23 Schema.decodeSync(Schema.fromJsonString(schema))(value);
24​
25const encode = <T, E>(schema: Schema.Codec<T, E>, value: T) =>
26 Schema.encodeSync(Schema.fromJsonString(schema))(value);
27​
28export const getLocalStorageItem = <T, E>(key: string, schema: Schema.Codec<T, E>): T | null => {
29 const item = isomorphicLocalStorage.getItem(key);
30 return item ? decode(schema, item) : null;
31};
32​
33export const setLocalStorageItem = <T, E>(key: string, value: T, schema: Schema.Codec<T, E>) => {
34 const valueToSet = encode(schema, value);
35 isomorphicLocalStorage.setItem(key, valueToSet);
36};
37​
38export const removeLocalStorageItem = (key: string) => {
39 isomorphicLocalStorage.removeItem(key);
40};
41​
42const LOCAL_STORAGE_CHANGE_EVENT = "t3code:local_storage_change";
43​
44interface LocalStorageChangeDetail {
45 key: string;
47​
48function dispatchLocalStorageChange(key: string) {
49 if (typeof window === "undefined") return;
50 window.dispatchEvent(
51 new CustomEvent<LocalStorageChangeDetail>(LOCAL_STORAGE_CHANGE_EVENT, {
52 detail: { key },
53 }),
54 );
56​
57export function useLocalStorage<T, E>(
58 key: string,
59 initialValue: T,
60 schema: Schema.Codec<T, E>,
61): [T, (value: T | ((val: T) => T)) => void] {
62 // Get the initial value from localStorage or use the provided initialValue
63 const [storedValue, setStoredValue] = useState<T>(() => {
64 try {
65 const item = getLocalStorageItem(key, schema);
66 return item ?? initialValue;
67 } catch (error) {
68 console.error("[LOCALSTORAGE] Error:", error);
69 return initialValue;
70 }
71 });
72​
73 // Return a wrapped version of useState's setter function that persists the new value to localStorage
74 const setValue = useCallback(
75 (value: T | ((val: T) => T)) => {
76 try {
77 setStoredValue((prev) => {
78 const valueToStore = typeof value === "function" ? (value as (val: T) => T)(prev) : value;
79 if (valueToStore === null) {
80 removeLocalStorageItem(key);
81 } else {
82 setLocalStorageItem(key, valueToStore, schema);
83 }
84 // Dispatch event after state update completes to avoid nested state updates
85 queueMicrotask(() => dispatchLocalStorageChange(key));
86 return valueToStore;
87 });
88 } catch (error) {
89 console.error("[LOCALSTORAGE] Error:", error);
90 }
91 },
92 [key, schema],
93 );
94​
95 const prevKeyRef = useRef(key);
96​
97 // Re-sync from localStorage when key changes
98 useEffect(() => {
99 if (prevKeyRef.current !== key) {
100 prevKeyRef.current = key;
101 try {
102 const newValue = getLocalStorageItem(key, schema);
103 setStoredValue(newValue ?? initialValue);
104 } catch (error) {
105 console.error("[LOCALSTORAGE] Error:", error);
106 }
107 }
108 }, [key, initialValue, schema]);
109​
110 // Listen for storage events from other tabs AND custom events from the same tab
111 useEffect(() => {
112 const syncFromStorage = () => {
113 try {
114 const newValue = getLocalStorageItem(key, schema);
115 setStoredValue(newValue ?? initialValue);
116 } catch (error) {
117 console.error("[LOCALSTORAGE] Error:", error);
118 }
119 };
120​
121 const handleStorageChange = (event: StorageEvent) => {
122 if (event.key === key) {
123 syncFromStorage();
124 }
125 };
126​
127 const handleLocalChange = (event: CustomEvent<LocalStorageChangeDetail>) => {
128 if (event.detail.key === key) {
129 syncFromStorage();
130 }
131 };
132​
133 window.addEventListener("storage", handleStorageChange);
134 window.addEventListener(LOCAL_STORAGE_CHANGE_EVENT, handleLocalChange as EventListener);
135​
136 return () => {
137 window.removeEventListener("storage", handleStorageChange);
138 window.removeEventListener(LOCAL_STORAGE_CHANGE_EVENT, handleLocalChange as EventListener);
139 };
140 }, [key, initialValue, schema]);
141​
142 return [storedValue, setValue];