Steven
Steven

Reputation: 5

How to keep the state even after refresh

I'm trying to pass the current state from one page to another and it works when I transferred it. However, the new problem is to keep the current state on the new page. Every time I refresh the page, the state is gone and keep getting an error says "cannot read property 'state' of undefined". I tried to use the useEffect from Hooks, but it still didn't work. Here's the step by step code:

My Product Page:

<Grid container direction="row" justify="center" alignItems="center">
  {currentSearch.map((productObj) => {
    // console.log(productObj);
    return (
      <ProductResult
        name={productObj.name}
        price={productObj.price}
        style={productObj.style}
        type={productObj.type}
        depth={productObj.depth}
        height={productObj.height}
        width={productObj.width}
      />
    );
  })}
</Grid>

Will be passed on to ProductResult component:

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

Then go to the product description:

const [loadInfo, setLoadInfoState] = useState('');
useEffect(() => {
  // loadDescrInfo();
  setLoadInfoState(props.location.infoObj.state);
}, []);
console.log(loadInfo);

Really appreciate any advice or help from y'all. Thank you

Upvotes: 0

Views: 321

Answers (1)

airblade
airblade

Reputation: 66

You need to save your state to localStorage or sessionStorage and when component mounts, pass the value from storage to your state. Read about localStorage: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Upvotes: 1

Related Questions