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 Kim
  • 251
  • 3
  • 5