From 795b92cc1a168c48c7710ca6e0e1ef5974013d95 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Thu, 26 Oct 2023 19:07:31 +0200 Subject: refactor(hooks): rewrite useLocalStorage hook * return a tuple instead of an object * add a validator function as parameter (if the stored value is manually changed, it is not safe to cast its type) * add tests --- src/utils/hooks/use-local-storage.tsx | 33 --------------------------------- 1 file changed, 33 deletions(-) delete mode 100644 src/utils/hooks/use-local-storage.tsx (limited to 'src/utils/hooks/use-local-storage.tsx') diff --git a/src/utils/hooks/use-local-storage.tsx b/src/utils/hooks/use-local-storage.tsx deleted file mode 100644 index 0f9fbb6..0000000 --- a/src/utils/hooks/use-local-storage.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { LocalStorage } from '../../services/local-storage'; -import { Dispatch, SetStateAction, useEffect, useState } from 'react'; - -export type UseLocalStorageReturn = { - value: T; - setValue: Dispatch>; -}; - -/** - * Use the local storage. - * - * @param {string} key - The storage local key. - * @param {T} [fallbackValue] - A fallback value if local storage is empty. - * @returns {UseLocalStorageReturn} An object with value and setValue. - */ -export const useLocalStorage = ( - key: string, - fallbackValue: T -): UseLocalStorageReturn => { - const getInitialValue = () => { - if (typeof window === 'undefined') return fallbackValue; - const storedValue = LocalStorage.get(key); - return storedValue ?? fallbackValue; - }; - - const [value, setValue] = useState(getInitialValue); - - useEffect(() => { - LocalStorage.set(key, value); - }, [key, value]); - - return { value, setValue }; -}; -- cgit v1.2.3