I am writing a custom hook for my react app . I have finished writing it but I dont know why the value of my constant preFixedKey is showing undefined. Plz help me.
import { useEffect, useState } from 'react'
const PREFIX = 'whatsapp-clone-'
const useLocalStorage = (key, initialValue) => {
const preFixedKey = PREFIX + key
const [value,setValue] = useState(
() => {
const localData = localStorage.getItem(preFixedkey)
if (localData != null) return JSON.parse(localData)
if ( typeof initialValue === 'function'){
return initialValue()
}else{
return initialValue
}
}
)
useEffect(
() => {
localStorage.setItem(preFixedKey,JSON.stringify(value))
},[preFixedKey,value]
)
return [value,setValue]
}
export default useLocalStorage;
useState. Instead you want to separate it into anotheruseEffect(with[]) deps, and thensetValue(initialValue), now you can't store functions in localStorage, or I mean it's theoretically possible to stringify a function but it's just not the right way to go about things. In fact JSON.stringify() will remove functions since functions are not part of JSON. There already exists useLocalStorage solutions that work if you want to use them.