i'm designing a e commerce, when comes the part to delete a item from the cart, i have this issue passing values from my return to my delete item from localStorage function
Specifically this error: Cart.jsx:24 Warning: Cannot update a component (
App) while rendering a different component (
Cart). To locate the bad setState() call inside
Cart, follow the stack trace as described in
I've been tryied to put my usestate Set method inside a useeffect with [], but doesnt works
well, here you have my code:
import React, { useEffect, useState } from "react";
import Navbar from "./Navbar";
import { Link } from "react-router-dom";
import Footer from "./Footer";
function Cart({ cart, setCart }) {
const newCart = cart.flatMap((c) => c);
const replaced = newCart.map(e => e.price.replaceAll('.', ''));
let sum = 0
replaced.forEach((price) => {
sum += price * 1;
});
let finalSum = sum.toLocaleString()
//function to recharge page when empty all the localStorage
function handleSubmit(e) {
e.preventDefault();
localStorage.clear();
window.location.reload();
}
//function to delete my product
function deleteProd(id){
const updCart = newCart.filter(e => e.id !==id)
setCart(updCart) //HERE IS THE ERROR
localStorage.setItem('cart', JSON.stringify(updCart))
}
return (
<>
<Navbar />
<h1>Carrito de Compras</h1>
<div className="cartWrapper">
{newCart.map((c) => (
<div className="cartProd">
<img src={c.img} alt="" />
<h1>{c.prod}</h1>
<h2>precio: ${c.price}</h2>
<Link to={`/products/${c.id}`}>Ver producto</Link>
<button onClick={deleteProd(c.id)}>Eliminar</button> //HERE I PASS THE PRODUCT ID TO MY FUNCTION
</div>
))}
<div className="right-bar">
<button onClick={handleSubmit}>Vaciar Carrito</button>
<h1>Total: ${finalSum}</h1>
</div>
</div>
<Footer />
</>
);
}
export default Cart;
Any respose will be received!!! thanks
Issue in code is in this line :
- <button onClick={deleteProd(c.id)}>Eliminar</button>
So whenever the cart component is getting rendered this function is directly getting executed which updates the cart state variable in parent component while rendering the Cart child component which is not allowed in react as updating the state variable while component is rendering which can cause unexpected results.
It is like you're writing something and suddenly your friend grabs your pen and starts updating the list which is not good.
Here's the solution for your issue.
Code with issue :
<button onClick={deleteProd(c.id)}>Eliminar</button> // Wrong function definition
Corrected code :
<button onClick={() => deleteProd(c.id)}>Eliminar</button> // Corrected code