Search code examples
javascriptreactjscomponentsstateuse-effect

localStorage state value of undefined after refresh


I'm trying to pass my state value to another page and store it to my localStorage. The state has been stored and it works the first time I run my application. However, my localStorage value keep saying undefined every time I refresh the page. For what I understand, the localStorage value will always be there until I delete the value in localStorage. I tried to modify my if/else statement inside my Hook useEffect function. Here's my code:

I'm passing state from this page using:

<Link to={{
                       pathname: "/product/description",
                       infoObj: {
                           text: "This is information passed on",
                           state: {
                               ...props
                           },
                       }
                   }}>
                        Product Description
                   </Link>

And I'm accessing the state from another page and set it to localStorageusing:

useEffect(() => {
    const stateInfo = JSON.stringify(props.location.infoObj);
    localStorage.setItem("info", stateInfo);
}, [])

This is how I access my item in my localStorage:

useEffect(() => {
    const getInfo = JSON.parse(localStorage.getItem("info"));
    if(!localStorage.getItem("info") || getInfo.length === 0){
        try{
            localStorage.setItem("info", JSON.stringify(props.location.infoObj));
        } catch (err){
            console.log(err);
        }
    }
},[])

Really appreciate helps from y'all


Solution

  • You are correct, localStorage will persist during the page refreshes or closing the page/browser, but the additional data that you pass during the page transition via location.infoObj won't. So what ends up happening is that your code overwrites the localStorage with the props.location.infoObj which will be undefined after a refresh.

    To fix it you can add additional condition in your first useEffect.

    useEffect(() => {
      const stateInfo = JSON.stringify(props.location.infoObj);
      if(stateInfo) {
        localStorage.setItem("info", stateInfo);
      }
    }, [])