0

I'm working on an e-commerce site with new Next 13 app route in that I am using react context and State Provider for managing state in the app. I want to that cart items persist even after refresh and data comes from local storage (for non-auth users) The setting of cart item to local sorage works fine (implemented by useEffect which listens cartItems)

However, the problem starts now, when I refresh the page, what i expect is that the initial state loads data from local storage and sets cartItems and then the UI updates and shows all the items. But the UI does not updates when cartItems is set from the local storage. I saw on console logging that cartItems is set succesfully and does contains the data required but the UI is not updated immediately. What I also found is that when the setCartItems (useState hook) runs again like for example adding new item in cart or changing quantity of item, then the data loaded from local storage and this new data all are shown.

This works fine in page route where the get data from local storage runs inside useEffect with empty dependency array. I tried this too but no changes. Also that when using local storage, I am getting that

- error context\StateContext.tsx (9:25) @ localStorage
- error ReferenceError: localStorage is not defined

The code

  //get data from local storage
   const localCartItems = localStorage.getItem("cartItems");
    const [cartItems, setCartItems] = useState<any>(
// if data exists in local storage then parse it and then pass as initial state, if not then return []
      localCartItems ? JSON.parse(localCartItems) : []
    );
  
  useEffect(() => {
    localStorage.setItem("cartItems", JSON.stringify(cartItems));
  }, [cartItems]);
Sohel Shekh
  • 241
  • 3
  • 9

0 Answers0