0

I am having issues pulling data from local storage in my next.js e-commerce app. Originally I am saving items to cart from within my cart-context file and with useReducer. In the cart provider component I am involving useEffect and setting the cartState to local storage with JSON.stringify(); I just learned that useReducer accepts a third argument that can return value and from the way I understand it, overrides the passing initial state. In this anonymous function I am making a call to localStorage to check if there is any "local data" and to return parsed local data if so. I am getting an error saying that local storage is not defined.. any help is greatly appreciated.

const CartProvider = (props) => {
  const [cartState, dispatchCartState] = useReducer(
    reducerFN,
    initialCartState,
    () => {
      let localData = localStorage.getItem("items");
      return localData ? JSON.parse(localData) : [];
    }
  );

  useEffect(() => {
    localStorage.setItem("items", JSON.stringify(cartState));
  }, [cartState]);


Felipe
  • 333
  • 7
  • 19
  • You can't set the reducer's initial state from `localStorage` on the server-side. Next.js pre-renders every page on the server, where Web APIs like `localStorage` aren't available. – juliomalves Jan 24 '22 at 15:31

1 Answers1

0

Try This In Context.js:

  useEffect(() => {
    if (JSON.parse(localStorage.getItem("state"))) {
      dispatch({
        type: INIT_STORED_CART,
        payload: JSON.parse(localStorage.getItem("state")),
      });
    }
  }, []);

  useEffect(() => {
    if (state !== initialState)
      localStorage.setItem("state", JSON.stringify(state));
  }, [state]);

And In reducer.js just return payload That it!, I Hop this helpful to you