react-localstorage-hooks
Version:
A collection of React hooks for reactively managing localStorage
52 lines (51 loc) • 2.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var react_1 = require("react");
var utils_1 = require("../utils");
;
/**
* Hook to create reactive state variables on `localStorage`.
*
* @param key key for localStorage
* @param opts Options object
* @returns a pair of current state and `setState` method to update the state.
*/
function useLocalStorageState(key, opts) {
var options = tslib_1.__assign({ initialState: undefined, sync: true }, opts);
var _a = react_1.useState(function () { var _a; return typeof window !== 'undefined' ? (_a = utils_1.deserialize(window.localStorage.getItem(key))) !== null && _a !== void 0 ? _a : options.initialState : options.initialState; }), state = _a[0], setState = _a[1];
var setStateWrapper = react_1.useCallback(function (newVal) {
if (typeof window === 'undefined')
return;
var result = newVal instanceof Function ? newVal(state) : newVal;
var serializedResult = utils_1.serialize(result);
window.localStorage.setItem(key, serializedResult);
// storage event is also triggered by the script so that synced hooks in the same window get up-to-date values
var event = new StorageEvent('storage', { key: key, newValue: serializedResult });
window.dispatchEvent(event);
setState(result);
}, [key, setState, state]);
var handleStorage = react_1.useCallback(function (event) {
var _a;
if (event.key === key && utils_1.deserialize(event.newValue) !== state) {
setState((_a = utils_1.deserialize(event.newValue)) !== null && _a !== void 0 ? _a : options.initialState);
}
}, [state, key, setState]);
react_1.useEffect(function () {
if (options.sync && typeof window !== 'undefined') {
window.addEventListener('storage', handleStorage);
return function () { return window.removeEventListener('storage', handleStorage); };
}
return function () { };
}, [handleStorage, options.sync]);
react_1.useEffect(function () {
if (typeof window === 'undefined')
return;
var storedData = utils_1.deserialize(window.localStorage.getItem(key));
if (storedData === null || storedData === undefined) {
window.localStorage.setItem(key, utils_1.serialize(options.initialState));
}
}, [key]);
return [state, setStateWrapper];
}
exports.default = useLocalStorageState;