UpaJah
UpaJah

Reputation: 7334

React useState hook - update state of a object

I have a checklist object state

const [checkList, setCheckList] = useState({checkA, checkB .. 100 checks})

How to update all states to e.target.checked at once? I should be able to update like this:

const handleAllCheck = (e) => {
Object.keys(checkList).map((resource) => {
  setCheckList({ ...checkList, [resource]: e.target.checked });
});

};

But this updates only one of 100 checks, What am I missing?

Upvotes: 0

Views: 75

Answers (2)

Drew Reese
Drew Reese

Reputation: 202608

Issues

You are enqueueing a bunch of state updates in a loop but not using a functional state update, so the same state from the current render cycle the updates are enqueued in is used for each update, overwriting the previous update. The last enqueued update wins and is the state set for the next render cycle.

const handleAllCheck = (e) => {
  Object.keys(checkList).map((resource) => {
    setCheckList({
      ...checkList, // <-- state from the previous render cycle
      [resource]: e.target.checked,
    });
  });
};

Solution

In order to update all the checked values you can simply forEach over the keys and use a functional state update to spread in the state from the previous enqueued update.

const handleAllCheck = (e) => {
  const { checked } = e.target;
  Object.keys(checkList).forEach((resource) => {
    setCheckList(checkList => ({
      ...checkList, // <-- state from the previous update
      [resource]: checked,
    }));
  });
};

Alternatively you can use a single update by reducing the old state into a new state object.

const handleAllCheck = (e) => {
  const { checked } = e.target;
  setCheckList(checkList => Object.keys(checkList).reduce(
    (checkList, resource) => ({
      ...checkList,
      [resource]: checked,
    }),
    {},
  ));
};

Upvotes: 2

masoodahm
masoodahm

Reputation: 305

can you try

const handleAllCheck = (e) => {
const newCheckList = Object.keys(checkList).map((resource) => {
  return e.target.checked;
});
setCheckList(newCheckList);

Upvotes: 0

Related Questions