( key: string, initialValue: T, namespace = defaultNamespace, extend = false )
| 30 | ); |
| 31 | |
| 32 | export default function useLocalStorage<T>( |
| 33 | key: string, |
| 34 | initialValue: T, |
| 35 | namespace = defaultNamespace, |
| 36 | extend = false |
| 37 | ): [T, Dispatch<SetStateAction<T>>] { |
| 38 | const [storedValue, setStoredValue] = useState(initialValue); |
| 39 | // We will use this flag to trigger the reading from localStorage |
| 40 | const [firstLoadDone, setFirstLoadDone] = useState(false); |
| 41 | |
| 42 | const prefixedKey = namespace + key; |
| 43 | |
| 44 | // Use an effect hook in order to prevent SSR inconsistencies and errors. |
| 45 | // This will update the state with the value from the local storage after |
| 46 | // the first initial value is applied. |
| 47 | useEffect(() => { |
| 48 | const fromLocal = () => { |
| 49 | if (typeof window === "undefined") { |
| 50 | return initialValue; |
| 51 | } |
| 52 | try { |
| 53 | const item = window.localStorage.getItem(prefixedKey); |
| 54 | return item |
| 55 | ? extend |
| 56 | ? ({ ...initialValue, ...JSON.parse(item) } as T) |
| 57 | : (JSON.parse(item) as T) |
| 58 | : initialValue; |
| 59 | } catch (error) { |
| 60 | console.error(error); |
| 61 | return initialValue; |
| 62 | } |
| 63 | }; |
| 64 | |
| 65 | // Set the value from localStorage |
| 66 | setStoredValue(fromLocal); |
| 67 | // First load is done |
| 68 | setFirstLoadDone(true); |
| 69 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 70 | }, [initialValue, prefixedKey]); |
| 71 | |
| 72 | const setLocalValue = useCallback( |
| 73 | (value: T) => { |
| 74 | if (!firstLoadDone) { |
| 75 | return; |
| 76 | } |
| 77 | |
| 78 | try { |
| 79 | if (typeof window !== "undefined") { |
| 80 | window.localStorage.setItem(prefixedKey, JSON.stringify(value)); |
| 81 | } |
| 82 | } catch (error) { |
| 83 | console.log(error); |
| 84 | } |
| 85 | }, |
| 86 | [firstLoadDone, prefixedKey] |
| 87 | ); |
| 88 | |
| 89 | const setValue: Dispatch<SetStateAction<T>> = useCallback( |
no outgoing calls
no test coverage detected