I have a hook with objects in an array and I want to change the value of key test
of the first object only.
const [Value, setValue] = useState([{test: 0}, {test: 0}]);
Also, I would like to be able to change a value from one to another at the click of a button, like toggle
. For example to get only 0
or 1
on click on one button.
Could you please tell me how to do it?
2
Answers
You can make a copy of the state in the callback of the set function.
Then alter index
0
with the new value and return the copy.As requested, on a click event:
As requested, on a click event with hard-coded values:
As requested, on a click event with toggle between 2 values
You could do this with immer lib which looks more clean and do normal array operations after that. As it under the hood creates copy of the original state and work on it.
You don’t need to copy with this apprach by your self, and not need to be concious if you are mistakenly using mutating method like
=[]
,push
etc. You can here use any methods from Array objects.