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

217
Vistas
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 Respuestas
Responde la pregunta

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