MCPcopy Create free account
hub / github.com/dailydotdev/apps / atomWithLocalStorage

Function atomWithLocalStorage

packages/shared/src/features/common/lib/jotai.ts:3–30  ·  view source on GitHub ↗
({
  key,
  initialValue,
  parseFunction,
}: {
  key: string;
  initialValue: T;
  parseFunction?: (value: string) => T;
})

Source from the content-addressed store, hash-verified

1import { atom } from 'jotai/vanilla';
2
3export const atomWithLocalStorage = <T>({
4 key,
5 initialValue,
6 parseFunction,
7}: {
8 key: string;
9 initialValue: T;
10 parseFunction?: (value: string) => T;
11}) => {
12 const getInitialValue = () => {
13 const item = globalThis?.localStorage?.getItem?.(key) ?? null;
14 if (item !== null) {
15 const value = JSON.parse(item);
16 return parseFunction?.(value) ?? (value as T);
17 }
18 return initialValue;
19 };
20 const baseAtom = atom<T>(getInitialValue());
21 return atom(
22 (get) => get(baseAtom),
23 (get, set, update) => {
24 const nextValue =
25 typeof update === 'function' ? update(get(baseAtom)) : update;
26 set(baseAtom, nextValue);
27 localStorage?.setItem?.(key, JSON.stringify(nextValue));
28 },
29 );
30};

Callers 1

funnel.store.tsFile · 0.90

Calls 4

getInitialValueFunction · 0.85
getFunction · 0.85
setFunction · 0.85
updateFunction · 0.50

Tested by

no test coverage detected