Benjamin
Benjamin

Reputation: 21

LocalStorage is empty in the 1st render NEXT.js

Im creating a shopping cart with NextJS and it works, but when I try to console log the length of my cart, in the first render it appears empty so it gives me a bunch of problems.

    const initialState = {};
  const [cart, setCart] = useState(initialState);

  useEffect(() => {
    const cartData = JSON.parse(localStorage.getItem("cart"));
    if (cartData) {
      setCart(cartData);
    }
  }, []);  

  useEffect(() => {
      localStorage.setItem("cart", JSON.stringify(cart));

  }, [cart]);

All cart methods such as DeleteCart, AddToCart, etc work fine. Any idea?

Upvotes: 1

Views: 1132

Answers (1)

Uéslei Suptitz
Uéslei Suptitz

Reputation: 400

You are 'almost' looping these two useEffect. Try this:

  const initialState = {};
  const [cart, setCart] = useState(initialState);

  useEffect(() => {
    const cartData = JSON.parse(localStorage.getItem("cart"));
    if (cartData) {
      setCart(cartData);
    }
  }, []);  

  useEffect(() => {
      if(Object.keys(cart).length > 0){
          localStorage.setItem("cart", JSON.stringify(cart));
      {
  }, [cart]);

Upvotes: 1

Related Questions