import createRegion from './createRegion' ; const localStorage = typeof window === 'object' && window . localStorage ; type Key = string ; type Value = any ; const setLocalStorageState = ( key , value ) => { const jsonString = JSON . stringify ( value ) ; if ( typeof jsonString === 'string' ) { localStorage && localStorage . setItem ( key , jsonString ) ; } else { localStorage && localStorage . removeItem ( key ) ; } } ; const getLocalStorageState = ( key , fallbackValue ) => { try { const jsonString = localStorage && localStorage . getItem ( key ) ; if ( jsonString === null ) { setLocalStorageState ( key , fallbackValue ) ; return fallbackValue ; } return JSON . parse ( jsonString ) ; } catch ( e ) { setLocalStorageState ( key , fallbackValue ) ; return fallbackValue ; } } ; const createLocalStorageRegion = < V > ( key , fallbackValue ) => { const region = createRegion < V > ( getLocalStorageState ( key , fallbackValue ) as V ) ; const regionSet = region . set ; region . set = valueOrFunc => { if ( typeof valueOrFunc === 'function' ) { const value = ( valueOrFunc as any ) ( getLocalStorageState ( key , fallbackValue ) ) ; setLocalStorageState ( key , value ) ; return regionSet ( value ) ; } setLocalStorageState ( key , valueOrFunc ) ; return regionSet ( valueOrFunc ) ; } ; typeof window === 'object' && window . addEventListener ( 'storage' , ( ) => { const value = getLocalStorageState ( key , fallbackValue ) ; regionSet ( value ) ; } ) ; return region ; } ; export default createLocalStorageRegion ;