F
F
F1eX2020-09-23 02:24:48
React
F1eX, 2020-09-23 02:24:48

Why is the checkbox state updated this way?

There is this code:

const rejectedCodes = {unverifiable: {status: false, code: 3}, ...}
const [rejectedStatuses, setRejectedStatuses] = useState(rejectedCodes);

<Checkbox
   checked={rejectedStatuses.unverifiable.status}
   onChange={(e) => {
        setRejectedStatuses({
             ...rejectedStatuses,
             unverifiable: { ...rejectedStatuses.unverifiable, status: e.target.checked }
       })
       console.log(rejectedStatuses);
   }}
>
Unverifiable
</Checkbox>


When you click on this checkbox, the state changes as it should, but the state of the checkbox itself is opposite to it - i.e. when status: true, the checked checkbox property is false and vice versa.
An attempt to cheat by inverting the state, of course, makes the checkbox unclickable.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-09-23
@F1eX

Because rejectedStatuses contains the state at the time of the last render. It cannot be changed by calling setRejectedStatuses, at least because it is a constant. And you check its value immediately after calling the setter function, as if the constant had changed once. It will change the next time the component's function is called, that is, after rendering caused by a state change.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question