2021-03-19 10:05:42 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { useEffect, useState } from '@wordpress/element';
|
2023-03-02 14:26:00 +00:00
|
|
|
import type { Dispatch, SetStateAction } from 'react';
|
2021-03-19 10:05:42 +00:00
|
|
|
|
|
|
|
export const useLocalStorageState = < T >(
|
|
|
|
key: string,
|
|
|
|
initialValue: T
|
2023-02-24 10:57:24 +00:00
|
|
|
): [ T, Dispatch< SetStateAction< T > > ] => {
|
2021-03-19 10:05:42 +00:00
|
|
|
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 ];
|
|
|
|
};
|