UNPKG

react-localstorage-hooks

Version:

A collection of React hooks for reactively managing localStorage

20 lines (19 loc) 736 B
import { deserialize, serialize } from '../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 = deserialize(window.localStorage.getItem(key)); var updatedData = serialize(reducer(data, action)); window.localStorage.setItem(key, updatedData); window.dispatchEvent(new StorageEvent('storage', { key: key, newValue: updatedData })); }; } export default createLocalStorageDispatch;