Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!