Skip to content

Commit 2541716

Browse files
committed
feat: 🎸 do work on useLocaStorage
There is some "Illegal invocation" that I cannot immediately solve, so postponing this hook for now.
1 parent 258d696 commit 2541716

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import {storiesOf} from '@storybook/react';
2+
import * as React from 'react';
3+
import {useLocalStorage} from '..';
4+
5+
const Demo = () => {
6+
const value = useLocalStorage('key');
7+
8+
return (
9+
<div>
10+
<div>Value: {value}</div>
11+
<button onClick={() => {(window.localStorage as any)['key'] = String(Date.now())}}>Update</button>
12+
</div>
13+
);
14+
};
15+
16+
storiesOf('useLocalStorage', module)
17+
.add('Example', () =>
18+
<Demo/>
19+
)

src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import useGeolocation from './useGeolocation';
77
import useHover from './useHover';
88
import useIdle from './useIdle';
99
import useList from './useList';
10+
import useLocalStorage from './useLocalStorage';
1011
import useLocation from './useLocation';
1112
import useMap from './useMap';
1213
import useMedia from './useMedia';
@@ -33,6 +34,7 @@ export {
3334
useHover,
3435
useIdle,
3536
useList,
37+
useLocalStorage,
3638
useLocation,
3739
useMap,
3840
useMedia,

src/useLocalStorage.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import {useState, useEffect} from './react';
2+
import {on, off} from './util';
3+
4+
const isClient = typeof window === 'object';
5+
6+
const useLocalStorage = (key: string): string | undefined => {
7+
if (!isClient) {
8+
return undefined;
9+
}
10+
11+
const [state, setState] = useState<string | undefined>(undefined);
12+
13+
useEffect(() => {
14+
try {
15+
setState(localStorage[key]);
16+
} catch {}
17+
18+
const onChange = (event) => {
19+
console.log('onChange')
20+
if (event.key === key) {
21+
setState(event.newValue);
22+
}
23+
}
24+
25+
on(window, 'storage', onChange);
26+
27+
return () => {
28+
off(window, 'storage', onChange);
29+
};
30+
}, [key]);
31+
32+
return state;
33+
};
34+
35+
export default useLocalStorage;

0 commit comments

Comments
 (0)