diff options
| author | Armand Philippot <git@armandphilippot.com> | 2022-05-24 19:35:12 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-05-24 19:35:12 +0200 |
| commit | c85ab5ad43ccf52881ee224672c41ec30021cf48 (patch) | |
| tree | 8058808d9bfca19383f120c46b34d99ff2f89f63 /src/utils/hooks/use-local-storage.tsx | |
| parent | 52404177c07a2aab7fc894362fb3060dff2431a0 (diff) | |
| parent | 11b9de44a4b2f305a6a484187805e429b2767118 (diff) | |
refactor: use storybook and atomic design (#16)
BREAKING CHANGE: rewrite most of the Typescript types, so the content format (the meta in particular) needs to be updated.
Diffstat (limited to 'src/utils/hooks/use-local-storage.tsx')
| -rw-r--r-- | src/utils/hooks/use-local-storage.tsx | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/src/utils/hooks/use-local-storage.tsx b/src/utils/hooks/use-local-storage.tsx new file mode 100644 index 0000000..da0292b --- /dev/null +++ b/src/utils/hooks/use-local-storage.tsx @@ -0,0 +1,35 @@ +import { LocalStorage } from '@services/local-storage'; +import { Dispatch, SetStateAction, useEffect, useState } from 'react'; + +export type UseLocalStorageReturn<T> = { + value: T; + setValue: Dispatch<SetStateAction<T>>; +}; + +/** + * Use the local storage. + * + * @param {string} key - The storage local key. + * @param {T} [fallbackValue] - A fallback value if local storage is empty. + * @returns {UseLocalStorageReturn<T>} An object with value and setValue. + */ +const useLocalStorage = <T extends unknown>( + key: string, + fallbackValue: T +): UseLocalStorageReturn<T> => { + const getInitialValue = () => { + if (typeof window === 'undefined') return fallbackValue; + const storedValue = LocalStorage.get<T>(key); + return storedValue || fallbackValue; + }; + + const [value, setValue] = useState<T>(getInitialValue); + + useEffect(() => { + LocalStorage.set(key, value); + }, [key, value]); + + return { value, setValue }; +}; + +export default useLocalStorage; |
