MCPcopy
hub / github.com/ampproject/amphtml / useLocalStorage

Function useLocalStorage

src/preact/hooks/useLocalStorage.ts:4–38  ·  view source on GitHub ↗
(
  key: string,
  defaultValue: T
)

Source from the content-addressed store, hash-verified

2import {logger} from '#preact/logger';
3
4export function useLocalStorage<T>(
5 key: string,
6 defaultValue: T
7): readonly [T, (newValue: T) => void] {
8 // Keep track of the state locally:
9 const [value, setValue] = useState(() => {
10 try {
11 const json = self.localStorage?.getItem(key);
12 return json ? JSON.parse(json) : defaultValue;
13 } catch (err) {
14 // warning: could not read from local storage
15 return defaultValue;
16 }
17 });
18
19 const storeValue = useCallback(
20 (newValue: T) => {
21 try {
22 const json = JSON.stringify(newValue);
23 self.localStorage?.setItem(key, json);
24 } catch (err) {
25 logger.warn(
26 'useLocalStorage',
27 'Could not write value to local storage',
28 key,
29 err
30 );
31 }
32 setValue(newValue);
33 },
34 [key]
35 );
36
37 return [value, storeValue] as const;
38}

Callers 1

BentoAppBannerFunction · 0.90

Calls 6

setValueFunction · 0.85
getItemMethod · 0.80
stringifyMethod · 0.80
setItemMethod · 0.80
warnMethod · 0.80
parseMethod · 0.45

Tested by

no test coverage detected