feature: useLocalStorage also update when the localStorage has been updated from other window
This commit is contained in:
parent
d2554bedf3
commit
1c6369677a
@ -19,7 +19,7 @@
|
|||||||
* @author Sebastian Javier Marchano (sebasjm)
|
* @author Sebastian Javier Marchano (sebasjm)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { StateUpdater, useState } from "preact/hooks";
|
import { StateUpdater, useEffect, useState } from "preact/hooks";
|
||||||
|
|
||||||
export function useLocalStorage(
|
export function useLocalStorage(
|
||||||
key: string,
|
key: string,
|
||||||
@ -33,6 +33,16 @@ export function useLocalStorage(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const listener = buildListenerForKey(key, (newValue) => {
|
||||||
|
setStoredValue(newValue ?? initialValue)
|
||||||
|
})
|
||||||
|
window.addEventListener('storage', listener)
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('storage', listener)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
const setValue = (
|
const setValue = (
|
||||||
value?: string | ((val?: string) => string | undefined),
|
value?: string | ((val?: string) => string | undefined),
|
||||||
): void => {
|
): void => {
|
||||||
@ -52,6 +62,13 @@ export function useLocalStorage(
|
|||||||
return [storedValue, setValue];
|
return [storedValue, setValue];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function buildListenerForKey(key: string, onUpdate: (newValue: string | undefined) => void): () => void {
|
||||||
|
return function listenKeyChange() {
|
||||||
|
const value = window.localStorage.getItem(key)
|
||||||
|
onUpdate(value ?? undefined)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
//TODO: merge with the above function
|
//TODO: merge with the above function
|
||||||
export function useNotNullLocalStorage(
|
export function useNotNullLocalStorage(
|
||||||
key: string,
|
key: string,
|
||||||
@ -63,6 +80,17 @@ export function useNotNullLocalStorage(
|
|||||||
: initialValue;
|
: initialValue;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const listener = buildListenerForKey(key, (newValue) => {
|
||||||
|
setStoredValue(newValue ?? initialValue)
|
||||||
|
})
|
||||||
|
window.localStorage.addEventListener('storage', listener)
|
||||||
|
return () => {
|
||||||
|
window.localStorage.removeEventListener('storage', listener)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
const setValue = (value: string | ((val: string) => string)): void => {
|
const setValue = (value: string | ((val: string) => string)): void => {
|
||||||
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
||||||
setStoredValue(valueToStore);
|
setStoredValue(valueToStore);
|
||||||
|
Loading…
Reference in New Issue
Block a user