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

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

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