MCPcopy Create free account
hub / github.com/msgbyte/tailchat / useStorageState

Function useStorageState

client/shared/hooks/factory/createUseStorageState.ts:22–83  ·  view source on GitHub ↗
(key: string, options?: Options<T>)

Source from the content-addressed store, hash-verified

20
21export function createUseStorageState(getStorage: () => Storage | undefined) {
22 function useStorageState<T>(key: string, options?: Options<T>) {
23 let storage: Storage | undefined;
24
25 // https://github.com/alibaba/hooks/issues/800
26 try {
27 storage = getStorage();
28 } catch (err) {
29 console.error(err);
30 }
31
32 const serializer = (value: T) => {
33 if (options?.serializer) {
34 return options?.serializer(value);
35 }
36 return JSON.stringify(value);
37 };
38
39 const deserializer = (value: string) => {
40 if (options?.deserializer) {
41 return options?.deserializer(value);
42 }
43 return JSON.parse(value);
44 };
45
46 function getStoredValue() {
47 try {
48 const raw = storage?.getItem(key);
49 if (raw) {
50 return deserializer(raw);
51 }
52 } catch (e) {
53 console.error(e);
54 }
55 if (_isFunction(options?.defaultValue)) {
56 return options?.defaultValue();
57 }
58 return options?.defaultValue;
59 }
60
61 const [state, setState] = useState<T>(() => getStoredValue());
62
63 useUpdateEffect(() => {
64 setState(getStoredValue());
65 }, [key]);
66
67 const updateState = (value: T | IFuncUpdater<T>) => {
68 const currentState = _isFunction(value) ? value(state) : value;
69 setState(currentState);
70
71 if (_isUndefined(currentState)) {
72 storage?.removeItem(key);
73 } else {
74 try {
75 storage?.setItem(key, serializer(currentState));
76 } catch (e) {
77 console.error(e);
78 }
79 }

Callers

nothing calls this directly

Calls 3

useMemoizedFnFunction · 0.90
getStoredValueFunction · 0.85
errorMethod · 0.80

Tested by

no test coverage detected