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

264
Vistas
Cannot add object by using setState to Array in React js

Code

........
........
  state = {
    users: [],
    currentUser: '',
    currentAge: '',
  };

........
........

  onSubmitHandler = (e) => {
   
    const Person = {
      name: this.state.currentUser, //already assign in another function 
      age: this.state.currentAge,//already assign in another function 
    };


    this.setState({
      users: [...this.state.users, Person],
    });
  
  };

  render() {
    return (
      <div>
        <h1></h1>
        <form onSubmit={this.onSubmitHandler}>
          <label>
            Enter your name:
            <input type="text" onChange={this.onChangeNameHandler} />
          </label>
          <br />
          <label>
            Enter your Age:
            <input type="number" onChange={this.onChangeAgeHandler} />
          </label>
          <br />
          <input type="submit" />
        </form>

        <ul>
          {this.state.users.map((user) => {
            return <UserCard name={user.name} age={user.age} />;
          })}
        </ul>
      </div>
    );
  }
}

Error

Warning: Each child in a list should have a unique "key" prop.

Check the render method of `UserForm`. See https://reactjs.org/link/warning-keys for more information.
at UserCard (https://react-3agtbk.stackblitz.io/~/src/components/UserCard.js:7:1)
at UserForm (https://react-3agtbk.stackblitz.io/~/src/components/UserForm.js:10:9)
at div
at App

I'm trying to add the Person Object to the users array. However, when I try to console.log(this.state.users), It always shows [ ]. I did add preventDefault in my onSubmitHandler function which solve the issue. In my another project, I did not add onSubmitHandler which still works. Why it happening ? Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Two problems:

  1. Nothing in onSubmitHandler is preventing the default action of the submit, which is to submit the form to the server and replace the page entirely with the result from the server.

    You need to add a call to e.preventDefault() to prevent the default action of the submit.

  2. Your setState call should be using the callback version:

    this.setState(({users, currentUser, currentAge}) => {
        const Person = {
            name: currentUser,
            age: currentAge,
        };
        return {users: [...users, Person]};
    });
    

    That's best practice any time you're updating state based on existing state.

Also, as a side note, initially-capped variable names in JavaScript code are almost universally reserved for constructor functions. The overwhelmingly-standard convention for just a local variable referring to an object is to use initial-lower-case (person, not Person).

Putting all of that together:

onSubmitHandler = (e) => {
    e.preventDefault();

    this.setState(({users, currentUser, currentAge}) => {
        const person = {
            name: currentUser,
            age: currentAge,
        };
        return {users: [...users, person]};
    });
};
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