LocalStorage includes an empty array on every render

I’m trying to update my localStorage with new items that are added to my shopping cart. However, every time an item is added, an empty array is added before it (see screenshot). Why is this?

I’m thinking I need to add a ternary operator to return an empty array if there are no existing items in the cart and to return the current items in the cart if there are items currently in localStorage. Is this correct, or do I have a syntax error?

Screenshot:
enter image description here

Code in question:

useEffect(() => {
  const newData = JSON.parse(localStorage.getItem('product')) || [];
  newData.push(cart);
  localStorage.setItem('product', JSON.stringify(newData));
}, [cart])

Full code:

import React, { useState, useEffect } from 'react';
import './../App.css';
import * as ReactBootStrap from 'react-bootstrap';

function Cart(props) {

    const [cart, setCart] = useState([]);
    const [quantity, setQuantity] = useState([]);
    const [loading, setLoading] = useState(false);

  useEffect(async () => {
  fetchItems();
}, [])

const itemId = props.match.params.id;
const itemQuantity = parseInt(props.match.params.qty, 10);
const fetchItems = async () => {
  const data = await fetch('https://fakestoreapi.com/products/' + itemId);
  const items = await data.json();
  setCart(items)
  setQuantity(itemQuantity)
  setLoading(true)
}

function price(qty){
  const newPrice = qty * cart.price;
  return newPrice.toFixed(2)
}

useEffect(() => {
  const newData = JSON.parse(localStorage.getItem('product')) || [];
  newData.push(cart);
  localStorage.setItem('product', JSON.stringify(newData));
}, [cart])

    return (
      <div>
        {loading ? (
          <div className="productStyle">
            <img src={cart.image} className="productImage"></img>
            <p>{cart.title}</p>

            <div className="quantity">
              <button className="btn minus-btn" type="button"
                onClick={quantity > 1 ? () => setQuantity(quantity - 1) : null}>-</button>
              <input type="text" id="quantity" placeholder={quantity}/>
              <button className="btn plus-btn" type="button"
                onClick={() => setQuantity(quantity + 1)}>+</button>
            </div>

            <p>${price(quantity)}</p>



          </div>
        ) : (<ReactBootStrap.Spinner className="spinner" animation="border" />)}
      </div>
    );
}

export default Cart;

34 thoughts on “LocalStorage includes an empty array on every render”

  1. 267678 865307An attention-grabbing discussion is worth comment. I believe which you ought to write far more on this matter, it wont be a taboo topic nevertheless normally persons are not sufficient to talk on such topics. Towards the next. Cheers 700515

    Reply

Leave a Comment