@magicbell/magicbell-react
Version:
React components for building a notification inbox for your app
53 lines • 2.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLocalStorage = useLocalStorage;
const tslib_1 = require("tslib");
// copy from: https://github.com/uidotdev/usehooks/blob/90fbbb4cc085e74e50c36a62a5759a40c62bb98e/index.js
const React = tslib_1.__importStar(require("react"));
function dispatchStorageEvent(key, newValue) {
window.dispatchEvent(new StorageEvent('storage', { key, newValue }));
}
function setLocalStorageItem(key, value) {
const stringifiedValue = JSON.stringify(value);
window.localStorage.setItem(key, stringifiedValue);
dispatchStorageEvent(key, stringifiedValue);
}
function removeLocalStorageItem(key) {
window.localStorage.removeItem(key);
dispatchStorageEvent(key, null);
}
function getLocalStorageItem(key) {
return window.localStorage.getItem(key);
}
function useLocalStorageSubscribe(callback) {
window.addEventListener('storage', callback);
return () => window.removeEventListener('storage', callback);
}
function getLocalStorageServerSnapshot() {
throw Error('useLocalStorage is a client-only hook');
}
function useLocalStorage(key, initialValue) {
const getSnapshot = () => getLocalStorageItem(key);
const store = React.useSyncExternalStore(useLocalStorageSubscribe, getSnapshot, getLocalStorageServerSnapshot);
const setState = React.useCallback((v) => {
try {
const nextState = typeof v === 'function' ? v(JSON.parse(store)) : v;
if (nextState === undefined || nextState === null) {
removeLocalStorageItem(key);
}
else {
setLocalStorageItem(key, nextState);
}
}
catch (e) {
console.warn(e);
}
}, [key, store]);
React.useEffect(() => {
if (getLocalStorageItem(key) === null && typeof initialValue !== 'undefined') {
setLocalStorageItem(key, initialValue);
}
}, [key, initialValue]);
return [store ? JSON.parse(store) : initialValue, setState];
}
//# sourceMappingURL=use-local-storage.js.map