UNPKG

@react-hookz/web

Version:

React hooks done right, for browser and SSR.

29 lines (28 loc) 1.08 kB
import { useStorageValue, } from "../useStorageValue/useStorageValue.js"; import { isBrowser, noop } from "../util/const.js"; let IS_LOCAL_STORAGE_AVAILABLE = false; try { IS_LOCAL_STORAGE_AVAILABLE = isBrowser && !!window.localStorage; } catch { // no need to test this flag leads to noop behaviour /* istanbul ignore next */ IS_LOCAL_STORAGE_AVAILABLE = false; } /** * Manages a single localStorage key. * * @param key Storage key to manage * @param defaultValue Default value to yield in case the key is not in storage * @param options */ export const useLocalStorageValue = IS_LOCAL_STORAGE_AVAILABLE ? (key, defaultValue = null, options = {}) => useStorageValue(localStorage, key, defaultValue, options) : (key, defaultValue = null, options = {}) => { /* istanbul ignore next */ if (isBrowser && process.env.NODE_ENV === 'development') { // eslint-disable-next-line no-console console.warn('LocalStorage is not available in this environment'); } return [undefined, noop, noop, noop]; };