UNPKG

react-localstorage-hooks

Version:

A collection of React hooks for reactively managing localStorage

34 lines (33 loc) 1.5 kB
import { __assign } from "tslib"; import { useCallback, useEffect, useState } from 'react'; import { deserialize } from '../utils'; ; /** * Hook to query an data stored in the localStorage and reactively update when it changes. * The hook only updates when the result of `selector` method changes. * * @param key Key of the localstorage store to be queried * @param selector Selector function to select items from the store * @param opts Options object * @returns Data queried by the `selector` method */ function useLocalStorageSelector(key, selector, opts) { var options = __assign({ equalityFn: function (prev, next) { return prev === next; } }, opts); var _a = useState(function () { return typeof window !== 'undefined' ? selector(deserialize(window.localStorage.getItem(key))) : undefined; }), state = _a[0], setState = _a[1]; var handleStorage = useCallback(function (event) { if (event.key !== key) return; var selectedData = selector(deserialize(event.newValue)); if (!options.equalityFn(state, selectedData)) { setState(selectedData); } }, [state, key, setState]); useEffect(function () { if (typeof window === 'undefined') return; window.addEventListener('storage', handleStorage); return function () { return window.removeEventListener('storage', handleStorage); }; }, [key, setState, handleStorage]); return state; } export default useLocalStorageSelector;