Create New Item
Item Type
File
Folder
Item Name
Search file in folder and subfolders...
Are you sure want to rename?
primogenial
/
wp-content
/
plugins
/
woocommerce
/
packages
/
woocommerce-blocks
/
assets
/
js
/
base
/
hooks
:
use-local-storage-state.ts
Advanced Search
Upload
New Item
Settings
Back
Back Up
Advanced Editor
Save
/** * External dependencies */ import { useEffect, useState } from '@wordpress/element'; export const useLocalStorageState = < T >( key: string, initialValue: T ): [ T, ( arg0: T ) => void ] => { const [ state, setState ] = useState< T >( () => { const valueInLocalStorage = window.localStorage.getItem( key ); if ( valueInLocalStorage ) { try { return JSON.parse( valueInLocalStorage ); } catch { // eslint-disable-next-line no-console console.error( `Value for key '${ key }' could not be retrieved from localStorage because it can't be parsed.` ); } } return initialValue; } ); useEffect( () => { try { window.localStorage.setItem( key, JSON.stringify( state ) ); } catch { // eslint-disable-next-line no-console console.error( `Value for key '${ key }' could not be saved in localStorage because it can't be converted into a string.` ); } }, [ key, state ] ); return [ state, setState ]; };