Home > Software engineering >  Unable to update empty array with formdata
Unable to update empty array with formdata

Time:11-08

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

CodePudding user response:

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.

  • Related