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

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

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