Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

79
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda