Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
React OnClick iteration

I want to do an onClick counter but I have a problem with the counter iterating correctly. In the app there are 3 "products" and after clicking "Add To Cart" button the state of the object is updated but all of the products are generated separately. I think that is cousing the problem where the counter is different for each of the products or everything will work correctly if I lift the state up, but the console.log is just freshly generated for all of the products. I'm not really sure so I need help with that.
Here is some code in the order from the parent to the last child:

import { useEffect, useState } from "react";
import ProductList from "./ProductList";

const Products = () => {
    const [products, setProducts] = useState (null);

    useEffect (() => {
        fetch('http://localhost:8000/products')
            .then(res => {
                return res.json();
            })
            .then(data => {
                setProducts(data);
            })
    }, []);
    
    return ( 
        <div className="ProductList">
            {products && <ProductList products={products}/>}
        </div>
    );
}

export default Products;
import Card from "./Card";

const ProductList = (props) => {
    const products = props.products;


    return ( 
        <div className="ProductList" >
            {products.map((product) => (
                <Card product={product} key={product.id} />))}
        </div>
    );
}

export default ProductList;
import { useState } from "react";

const Card= ({ product }) => {
    const [showDescription, setShowDescription] = useState(false);
    const [CartCounter, setCartCounter ] = useState(0);

    console.log(CartCounter);

    return (
    <div className="Product-Preview" >
        <div className="backdrop" style={{ backgroundImage: `url(${product.image})` }}></div>
        <h2>{product.title}</h2>
        <div>{product.price}</div>
        <button className="ShowDescription" onClick={() => setShowDescription(!showDescription)}>Details</button>
        <button className="AddToCart" onClick={() => setCartCounter(CartCounter + 1)}>Add To Cart </button> 
        {showDescription && <p>{product.description}</p>}
        <br />
    </div>
    );
};

export default Card;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Ok, you want to keep track of an aggregated value. I'll list code in some high level.

  const ProductList = () => {
    const [count, setCount] = useState(0)
    const addOrRemove = n => { setCount(v => v + n) }

    return products.map(p => <Card addOrRemove={addOrRemove} />)
  }

  const Card = ({ addOrRemove }) => {
    // optional if you want to track card count
    // const [count, setCount] = useState(0)
    
    return (
      <>
         <button onClick={() => { addOrRemove(1) }>Add</button>
         <button onClick={() => { addOrRemove(-1) }>Remove</button>
      </>
    )
  }

Essentially either you track the local count or not, you need to let the parent to decide what is the final count, otherwise there'll be some out of sync issue between the child and parent.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda