Search code examples
javascriptreactjsarraysjavascript-objects

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.


Solution

  • 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] });