Accept a function in writeStorage as well as an object/string
mayteio opened this issue · comments
Harley Alexander commented
In the basic useState hook, you can access current state when setting the next state like so:setState(prev => !prev)
This is handy when you're using it within a useEffect
so you don't need to add the extra dependency.
Would something like this work? I can create a PR if so;
export function writeStorage<TValue>(key: string, value: TValue) {
try {
// check for a function, run it with the current value;
if (typeof value === "function") {
const existingState = localStorage.getItem(key);
value = value(existingState);
}
localStorage.setItem(key, typeof value === 'object' ? JSON.stringify(value) : `${value}`);
window.dispatchEvent(new LocalStorageChanged({ key, value }));
} catch(err) {
...
}
}```
Amit Solanki commented
If you are getting value directly from local storage, you can do the same inside the useEffect without adding any dependency.