1

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

1 Answer 1

3

Map the array state to create a new array state. If the item being iterated over has an ID that matches, return the updated object from the callback, otherwise return the existing item.

const updateCheck = (id) => setArr(
  arr.map(item => (
    item.id !== id ? item : { ...item, checked: !item.checked }
  ))
);
Sign up to request clarification or add additional context in comments.

2 Comments

What about if the array has 1000000 records and the one I'm looking for is in the first cell of the array?
The code will still work, but such large arrays generally shouldn't exist on the frontend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.