useRef to track internal ready state for localStorage
This commit is contained in:
parent
5841be88ea
commit
a15a0711bc
1 changed files with 10 additions and 4 deletions
|
@ -1,4 +1,4 @@
|
|||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
|
||||
// See: https://usehooks.com/useLocalStorage/
|
||||
function useLocalStorage(key, initialValue) {
|
||||
|
@ -6,13 +6,16 @@ function useLocalStorage(key, initialValue) {
|
|||
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 readyInternal = useRef(false);
|
||||
|
||||
const setValue = function (value) {
|
||||
if (!readyInternal.current) {
|
||||
return null
|
||||
}
|
||||
|
||||
const setValue = (value) => {
|
||||
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)
|
||||
|
@ -21,9 +24,12 @@ function useLocalStorage(key, initialValue) {
|
|||
|
||||
// get the item from localstorage after the component has mounted. empty brackets mean it runs one time
|
||||
useEffect(() => {
|
||||
readyInternal.current = true;
|
||||
const item = window.localStorage.getItem(prefix + key)
|
||||
if (item) {
|
||||
setValue(JSON.parse(item));
|
||||
} else if (storedValue) {
|
||||
setValue(storedValue)
|
||||
}
|
||||
setReady(true);
|
||||
}, [])
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue