File tree 3 files changed +56
-0
lines changed 3 files changed +56
-0
lines changed Original file line number Diff line number Diff line change
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
+ )
Original file line number Diff line number Diff line change @@ -7,6 +7,7 @@ import useGeolocation from './useGeolocation';
7
7
import useHover from './useHover' ;
8
8
import useIdle from './useIdle' ;
9
9
import useList from './useList' ;
10
+ import useLocalStorage from './useLocalStorage' ;
10
11
import useLocation from './useLocation' ;
11
12
import useMap from './useMap' ;
12
13
import useMedia from './useMedia' ;
@@ -33,6 +34,7 @@ export {
33
34
useHover ,
34
35
useIdle ,
35
36
useList ,
37
+ useLocalStorage ,
36
38
useLocation ,
37
39
useMap ,
38
40
useMedia ,
Original file line number Diff line number Diff line change
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 ;
You can’t perform that action at this time.
0 commit comments