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

266
Visualizações
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 Respostas
Responde à pergunta

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