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

useLocalStorage.ts

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