dimanche 27 septembre 2020

How to find the total price from a list of items in React?

I am working on an ecommerce website in React. When a user adds a product in his cart, the state of cart get's updated. It looks like this -

const[cart, setCart] = useState([]);

everything works fine, the cart is updated with the help of Firestore. Each item in the cart has properties - id, image, productName and productPrice

I want to display the total price (sum of prices of all the items in the cart). What I try to do is this -

const getCartTotal = () => {
    let total = 0;
    {
      cart?.map((item) => total + item.productPrice);
    }
  };

But this give me an error in the browser -

Line 37:7:  Expected an assignment or function call and instead saw an expression  no-unused-expressions

What should the correct approach be? Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire