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

214
Views
i getting an error which Cannot read properties of undefined (reading 'push') in react

  24 |     lastname: lname
  25 |   };
  26 |  
> 27 |   setobj(obj.data.push(dat));
     |                  ^
  28 |   console.log(obj);
  29 | };
  30 | 

i did not getting for the first time but when I again write the form value and submit it shows me this issues. down there is my full code.


function App() {
  
  var [obj, setobj] = useState({
    data: [
      {
        name: "chetan",
        lastname: "vashisht"
      }
    ]
  });

  var [name, setname] = useState("");
  var [lname, setlname] = useState("");

  const handle = (e) => {
    e.preventDefault();
    const dat = {
      name: name,
      lastname: lname
    };
   
    setobj(obj.data.push(dat));
    console.log(obj);
  };

  return (
    <div className="App">
      <form onSubmit={handle}>
        <label>Enter your name:</label>
        <input
          id="ing"
          type="text"
          value={name}
          onChange={(e) => setname(e.target.value)}
          required
          autoFocus
        />
        <br />
        <label>Enter last name:</label>
        <input
          type="text"
          value={lname}
          onChange={(e) => setlname(e.target.value)}
          required
        />
        <br />
        <button>Sign in</button>
      </form>
    </div>
  );
}




here I made an state which is the object using useState() where i have to store the data in the obj.data so I used the .push() method for storing the data . it works fine at first but then if i store values again it shows me error.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You should always pass a new value to setobj.

setobj(obj.data.push(dat));

Here you are passing return value of push which is length of obj.data which will be primitive of type number. so next time when you again click signin button you are trying to access push on undefined value.

SOULTION

CODESANDBOX DEMO

Instead you should set state as:

setobj({ ...obj, data: [...obj.data, dat] });
about 4 years ago · Santiago Trujillo 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!