File "use-local-storage-state.ts"

Full Path: /home/vantageo/public_html/cache/cache/cache/cache/cache/.wp-cli/wp-content/plugins/woocommerce/packages/woocommerce-blocks/assets/js/base/hooks/use-local-storage-state.ts
File size: 966 bytes
MIME-type: text/x-java
Charset: utf-8

/**
 * 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 ];
};