1

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;
4
  • it is a custom hook and I have defined the value of key and initialValue later Commented Oct 14, 2020 at 17:09
  • 1
    That's not how you use useState . Instead you want to separate it into another useEffect (with []) deps, and then setValue(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. Commented Oct 14, 2020 at 17:11
  • Sorry,but its not the correct answer Commented Oct 14, 2020 at 17:18
  • sorry i thought you were trying to save function into localStorage. even so, it looks wrong. Commented Oct 14, 2020 at 18:23

1 Answer 1

1

TYPO

  • should be preFixedKey instead of preFixedkey
 const localData = localStorage.getItem(preFixedKey)

inside the useState

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.