react-localstorage-hooks
Version:
A collection of React hooks for reactively managing localStorage
22 lines (21 loc) • 816 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("../utils");
/**
* A function to create a dispatcher that updates data stored on localStorage.
*
* @param key key for localStorage
* @param reducer reducer method that returns new data
* @returns a dispatch method
*/
function createLocalStorageDispatch(key, reducer) {
return function (action) {
if (typeof window === 'undefined')
return;
var data = utils_1.deserialize(window.localStorage.getItem(key));
var updatedData = utils_1.serialize(reducer(data, action));
window.localStorage.setItem(key, updatedData);
window.dispatchEvent(new StorageEvent('storage', { key: key, newValue: updatedData }));
};
}
exports.default = createLocalStorageDispatch;