Skip to content
Advertisement

When a button in React is clicked, the component renders twice

I’m pretty new to React, and I’m making an ecommerce website for practice. I have a cart component that dynamically renders cart items from an API, but I narrowed the problem 100% down to the front end. On the initial render, it works fine, everything that is in the database cart appears, however after I press the “Delete from Cart” button on a cart item, each cart item doubles.

CartCard.jsx (/api/delete returns a json object of the cart AFTER deletion. deletion is handled in the api)

JavaScript

Cart.jsx:

JavaScript

Profile.jsx:

JavaScript

App.jsx

JavaScript

Thanks for your help

Advertisement

Answer

This for loop might be the issue:

JavaScript

Keep in mind that setState in react is asynchronous. What it means:

JavaScript

Try changing your for loop into that:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement