1
0
Fork 0

add some comments

This commit is contained in:
Enoch Riese 2022-06-06 13:20:24 -05:00
parent 45e83c0225
commit 9f7452dcc7
2 changed files with 6 additions and 1 deletions

View file

@ -4,19 +4,22 @@ import { useState, useEffect } from 'react'
function useLocalStorage(key, initialValue) {
const prefix = 'fs_'
const [storedValue, setStoredValue] = useState(initialValue);
// use this to track whether it's mounted. useful for doing other effects outside this hook
const [ready, setReady] = useState(false);
const setValue = (value) => {
if (typeof window === 'undefined') return null // SSR has no window object
if (!ready) return null
try {
const valueToStore = value instanceof Function ? value(storedValue) : value
setStoredValue(valueToStore)
window.localStorage.setItem(prefix + key, JSON.stringify(valueToStore))
} catch (error) {
console.log(error)
}
}
// get the item from localstorage after the component has mounted. empty brackets mean it runs one time
useEffect(() => {
const item = window.localStorage.getItem(prefix + key)
if (item) {