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

198
Visualizações
Unable to update empty array with formdata

I am currently trying to store the data attached to buttons on the site when a user clicks on them. I am using onClick function to grab the data passed in from the button and I am attempting to set it in state. The issue I am running into; however, is that the state value is not updating for whatever reason and it remains an empty array. My desired result if the object exists in the array, update it. If it does not, append to the array. Any guidance as to why state is not updating properly would be greatly appreciated. My code is as follows:

import { useState } from "react";

export default function App() {
  const [formData, setFormData] = useState([]);
  const data = [
    { name: "test1", id: 1, isActive: false },
    { name: "test2", id: 2, isActive: false }
  ];

  const handleClick = (item) => {
    setFormData(
      (formData) =>
        formData.map((res) =>
          res?.id === item.id
            ? { ...res, checked: !res.isActive }
            : { ...item, checked: !item.isActive }
        )
    );
  };

  return (
    <div className="App">
      {data.map((item) => {
        return <button onClick={() => handleClick(item)}>{item.name}</button>;
      })}
    </div>
  );
}

attached is a code sandbox for debugging: https://codesandbox.io/s/peaceful-sun-20ec0?file=/src/App.js:0-681

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think the main issue is that you are initializing formData to be an empty array. This makes the map call on formData in handleClick do nothing, because calling map on an empty array will not call the map function on any elements.

about 4 years ago · Juan Pablo Isaza 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