0

How can i fix this? i'm trying to almacenate my cartItems state in the localStorage but nextJs throw me localstorage is not defined error.

const initialState = {
  cartItems: localStorage.getItem("cartItems")
    ? JSON.parse(localStorage.getItem("cartItems"))
    : [],
  cartTotalQuantity: 0,
  cartTotalAmout: 0,
};

1 Answers1

2

localStorage is defined only in browsers (of course!)

in Next.js, your code is run both in the browser and the server.

You can safely initialize and use your state in useEffect hook like this

function MyComponent() {
  const [myState, setMyState] = React.useState({ cartItems: [], cartTotalQuantity: 0, cartTotalAmount: 0 });

  // This code runs after the component mounted
  React.useEffect(() => {
    const cartItemsString = localStorage.get('cartItems');

    if (cartItemsString) {
      setMyState((prev) => ({ ...prev, cartItems: JSON.parse(cartItemsString) }))
    }
  }, [])

  return <>YOUR JSX GOES HERE</>
}
Kay
  • 789
  • 1
  • 6
  • 6
  • but we're not allowed to write useEffect hook inside of a redux store, how can we do that then? – Mohit Dec 30 '22 at 08:39