use-local-storage-state
Advanced tools
Comparing version 0.4.0 to 1.0.0
import { Dispatch, SetStateAction } from 'react'; | ||
export default function useLocalStorageState<T>(key: string, defaultValue?: T): [T, Dispatch<SetStateAction<T>>]; | ||
export declare function createLocalStorageStateHook<T>(name: string, defaultValue?: T): () => [T, Dispatch<SetStateAction<T>>]; |
@@ -5,18 +5,17 @@ "use strict"; | ||
function useLocalStorageState(key, defaultValue) { | ||
const globalKey = `use-local-storage-state.${key}`; | ||
const [value, setValue] = react_1.useState(() => { | ||
const storageValue = localStorage.getItem(globalKey); | ||
const storageValue = localStorage.getItem(key); | ||
return storageValue === null ? defaultValue : JSON.parse(storageValue); | ||
}); | ||
const updateValue = (newValue) => { | ||
const updateValue = react_1.useCallback((newValue) => { | ||
setValue(value => { | ||
const isCallable = (value) => typeof value === 'function'; | ||
const result = isCallable(newValue) ? newValue(value) : newValue; | ||
localStorage.setItem(globalKey, JSON.stringify(result)); | ||
localStorage.setItem(key, JSON.stringify(result)); | ||
return result; | ||
}); | ||
}; | ||
}, [key]); | ||
react_1.useLayoutEffect(() => { | ||
const onStorage = (e) => { | ||
if (e.storageArea === localStorage && e.key === globalKey) { | ||
if (e.storageArea === localStorage && e.key === key) { | ||
setValue(e.newValue === null ? defaultValue : JSON.parse(e.newValue)); | ||
@@ -31,1 +30,18 @@ } | ||
exports.default = useLocalStorageState; | ||
function createLocalStorageStateHook(name, defaultValue) { | ||
const updates = []; | ||
return function useLocalStorageStateHook() { | ||
const [value, setValue] = useLocalStorageState(name, defaultValue); | ||
const updateValue = react_1.useCallback((newValue) => { | ||
for (const update of updates) { | ||
update(newValue); | ||
} | ||
}, []); | ||
react_1.useLayoutEffect(() => { | ||
updates.push(setValue); | ||
return () => void updates.splice(updates.indexOf(setValue), 1); | ||
}, [setValue]); | ||
return [value, updateValue]; | ||
}; | ||
} | ||
exports.createLocalStorageStateHook = createLocalStorageStateHook; |
{ | ||
"name": "use-local-storage-state", | ||
"version": "0.4.0", | ||
"version": "1.0.0", | ||
"description": "React hook for local storage state done right", | ||
@@ -5,0 +5,0 @@ "license": "MIT", |
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
6222
48
1