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

78
Visualizações
Adding object inside state's array

I'm trying to add an object in the array defined in the state, which (object) I get from a child then moving up to the parent, setting it to parent's state and giving it to another(that child's code is down below) child as a prop. I saw some solutions but they are not working. The present solution gives me an infinite loop, props item is added over and over. So my question is how to add an item in the array which is defined in the state and the item that we are getting is a prop. Here's my code

import React, { Component } from "react";

import "./ShoppingCart.css";



class ShoppingCart extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      items: [],
    };
  }


  

  onAddItem = () => {

    if(Object.keys(this.props.item).length !== 0)
    //checking initial empty prop
    {

      const item = this.props.item;
      //an object consist of {id,title,price...etc}
      
      //the solution i found on the internet
      const newList = this.state.items.concat(item);
      console.log("New List",newList);
  
      this.setState({
        items:newList
      })

    }


  };

  render() {
    this.onAddItem();
    return (
      <React.Fragment>
        <button className="cart-button">
          <img className="shopping-cart-img" src="./images/shopping-cart.png" />
          {/* Here will be some code*/}
        </button>
      </React.Fragment>
    );
  }
}

export default ShoppingCart;

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are calling the function on every render and then setting state, causing another render, and then the render call the function again.... it's an infinite loop.

  render() {
    this.onAddItem(); // ❌ REMOVE THIS LINE
    return (
      <React.Fragment>
        <button className="cart-button" onClick={this.onAddItem}> //✅ add onclick event to add item here
          <img className="shopping-cart-img" src="./images/shopping-cart.png" />
          {/* Here will be some code*/}
        </button>
      </React.Fragment>
    );

Update constructor

constructor(props) {
super(props);

this.state = {
  items: [],
};
this.onAddItem = this.onAddItem.bind(this)

}

Updated onAddItem

 onAddItem = (item) => {
    
    const newList = [...this.props.item, item]
    
  
      this.setState({
        items: newList
      })

    }


  };
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