UNPKG

beautiful-react-hooks

Version:

A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development

55 lines (54 loc) 2.13 kB
import { useCallback, useState } from 'react'; import safelyParseJson from '../shared/safelyParseJson'; import isClient from '../shared/isClient'; import isAPISupported from '../shared/isAPISupported'; import isDevelopment from '../shared/isDevelopment'; import noop from '../shared/noop'; /** * An utility to quickly create hooks to access both Session Storage and Local Storage */ const createStorageHook = (type) => { const storageName = `${type}Storage`; if (isClient && !isAPISupported(storageName)) { // eslint-disable-next-line no-console console.warn(`${storageName} is not supported`); } /** * the hook */ return function useStorageCreatedHook(storageKey, defaultValue) { if (!isClient) { if (isDevelopment) { // eslint-disable-next-line no-console console.warn(`Please be aware that ${storageName} could not be available during SSR`); } return [JSON.stringify(defaultValue), noop]; } const storage = (window)[storageName]; const safelySetStorage = useCallback((valueToStore) => { try { storage.setItem(storageKey, valueToStore); // eslint-disable-next-line no-empty } catch (e) { } }, [storage, storageKey]); const [storedValue, setStoredValue] = useState(() => { let valueToStore; try { valueToStore = storage.getItem(storageKey) || JSON.stringify(defaultValue); } catch (e) { valueToStore = JSON.stringify(defaultValue); } safelySetStorage(valueToStore); return safelyParseJson(valueToStore); }); const setValue = useCallback((value) => { const valueToStore = value instanceof Function ? value(storedValue) : value; safelySetStorage(JSON.stringify(valueToStore)); setStoredValue(valueToStore); }, [safelySetStorage, storedValue]); return [storedValue, setValue]; }; }; export default createStorageHook;