UNPKG

@rehooks/local-storage

Version:
69 lines 3.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useLocalStorage = void 0; var local_storage_events_1 = require("./local-storage-events"); var is_browser_1 = require("./is-browser"); var storage_1 = require("./storage"); var react_1 = require("react"); /** * This exists for trying to serialize the value back to JSON. * If it cannot serialize it, then it was a string value given. * * @param value the value you wish to try to parse */ function tryParse(value) { try { return JSON.parse(value); } catch (_a) { return value; } } function useLocalStorage(key, defaultValue) { if (defaultValue === void 0) { defaultValue = null; } var _a = react_1.useState(storage_1.storage.getItem(key) === null ? defaultValue : tryParse(storage_1.storage.getItem(key))), localState = _a[0], updateLocalState = _a[1]; var onLocalStorageChange = react_1.useCallback(function (event) { // An event value can be of TValue when `localStorage.setItem` is called, or null when // `localStorage.removeItem` is called. if (local_storage_events_1.isTypeOfLocalStorageChanged(event)) { if (event.detail.key === key) { updateLocalState(event.detail.value); } } else { if (event.key === key) { updateLocalState(event.newValue === null ? null : tryParse(event.newValue)); } } }, [updateLocalState, key]); react_1.useEffect(function () { if (!is_browser_1.isBrowser()) { return; } // The custom storage event allows us to update our component // when a change occurs in localStorage outside of our component var listener = function (e) { onLocalStorageChange(e); }; window.addEventListener(local_storage_events_1.LOCAL_STORAGE_CHANGE_EVENT_NAME, listener); // The storage event only works in the context of other documents (eg. other browser tabs) window.addEventListener('storage', listener); // Write default value to the local storage if there currently isn't any value there. // Don't however write a defaultValue that is null otherwise it'll trigger infinite updates. if (storage_1.storage.getItem(key) === null && defaultValue !== null) { local_storage_events_1.writeStorage(key, defaultValue); } return function () { window.removeEventListener(local_storage_events_1.LOCAL_STORAGE_CHANGE_EVENT_NAME, listener); window.removeEventListener('storage', listener); }; }, [key, defaultValue, onLocalStorageChange]); var writeState = react_1.useCallback(function (value) { return value instanceof Function ? local_storage_events_1.writeStorage(key, value(localState)) : local_storage_events_1.writeStorage(key, value); }, [key]); var deleteState = react_1.useCallback(function () { return local_storage_events_1.deleteFromStorage(key); }, [key]); var state = localState !== null && localState !== void 0 ? localState : defaultValue; return [state, writeState, deleteState]; } exports.useLocalStorage = useLocalStorage; //# sourceMappingURL=use-localstorage.js.map