Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 won’t update the array.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading