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/
|
// See: https://usehooks.com/useLocalStorage/
|
||||||
function useLocalStorage(key, initialValue) {
|
function useLocalStorage(key, initialValue) {
|
||||||
|
@ -6,13 +6,16 @@ function useLocalStorage(key, initialValue) {
|
||||||
const [storedValue, setStoredValue] = useState(initialValue);
|
const [storedValue, setStoredValue] = useState(initialValue);
|
||||||
// use this to track whether it's mounted. useful for doing other effects outside this hook
|
// use this to track whether it's mounted. useful for doing other effects outside this hook
|
||||||
const [ready, setReady] = useState(false);
|
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 {
|
try {
|
||||||
const valueToStore = value instanceof Function ? value(storedValue) : value
|
const valueToStore = value instanceof Function ? value(storedValue) : value
|
||||||
setStoredValue(valueToStore)
|
setStoredValue(valueToStore)
|
||||||
|
|
||||||
window.localStorage.setItem(prefix + key, JSON.stringify(valueToStore))
|
window.localStorage.setItem(prefix + key, JSON.stringify(valueToStore))
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(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
|
// get the item from localstorage after the component has mounted. empty brackets mean it runs one time
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
readyInternal.current = true;
|
||||||
const item = window.localStorage.getItem(prefix + key)
|
const item = window.localStorage.getItem(prefix + key)
|
||||||
if (item) {
|
if (item) {
|
||||||
setValue(JSON.parse(item));
|
setValue(JSON.parse(item));
|
||||||
|
} else if (storedValue) {
|
||||||
|
setValue(storedValue)
|
||||||
}
|
}
|
||||||
setReady(true);
|
setReady(true);
|
||||||
}, [])
|
}, [])
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue