'React - Set state object using args
I have an object saved in a state I am trying to create a function to update parts of the object.
function removeError(val) {
setPersonsState((prevState) => ({
...prevState,
val: "",
}));
}
I have tried to pass val to the object key to update it.
onClick={removeError('Bob')}
Where Bob replaces val to update in the object. Sorry if terminology is bad.
Solution 1:[1]
Well, you should change it to be in the following way, sine you don't want to change a key named val, but the key with name equal to the value of val
function removeError(val) {
setPersonsState((prevState) => ({
...prevState,
[val]: "",
}));
}
And, as suggested in the comments by @RoshanKanwar, also the click handler is not correct, it should be
onClick = {() => removeError('Bob')}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Emanuele Scarabattoli |
