I currently have an array of objects. Each array of objects contains a key of checked with a value of type boolean. I am attempting to loop through the array when a user selects a certain checkbox and updating that objects checked value to either true or false. The issue I am having is spreading the updated object back into the array without creating duplicates. My code is as follows:
import { useState } from "react";
import "./styles.css";
export default function App() {
const [arr, setArr] = useState([
{ id: 1, checked: false, name: "Person 1" },
{ id: 2, checked: true, name: "Person 2" }
]);
const updateCheck = (id) => {
const newArr = [...arr];
const object = newArr.find((r) => r.id === id);
const updatedObject = { ...object, checked: !object.checked };
console.log(updatedObject);
};
return (
<div className="App">
{arr.map((r) => {
return (
<>
<label>{r.name}</label>
<input
type="checkbox"
checked={r.checked}
onClick={() => updateCheck(r.id)}
/>
<br />
</>
);
})}
</div>
);
}
The desired effect I would like to achieve is that if Person 1's checkbox gets clicked I update their checked value to the opposite value. So Person 1 would have a checked value of true after their checkbox was clicked.
attached is a code sandbox https://codesandbox.io/s/elegant-haibt-hycmy?file=/src/App.js