I have an handlechange function
const [values, SetValues] = useState({
addrId: "",
addrType: "",
addrLine1: "",
addrLine2: "",
countryId: "",
stateId: "",
countyId: "",
zip: "",
});
const handleChange = (e) => {
const { name, value } = e.target;
SetValues({
...values,
[name]: value,
});
};
I tried to update some field(countryID) using other functions say handleAnotherFunction
const handleAnotherFunction=async(event)=>
{
SetValues({ ...values, [values.countryId]: 130 });
}
But value is not updated any help would be appreciated
2
Answers
This syntax:
uses the value of the variable
name
as the object key. So, for example, ifname
has the value"foo"
then it creates or updates the keyfoo
to the value ofvalue
:So, when you use this same syntax:
It uses the value of
values.countryId
as the object key. So if that value is, for example,100
then you’re adding a key to the object called100
and giving it the value130
:If you want to explicitly update the field
countryId
, just usecountryId
:So the whole line would be:
so what’s the purpose of creating
handleChange
?The
handleChange
in your code is designed to update the state based on the given value as parameter.it destructs the key and the value from the property
target
of the given object then updates the state. so if you want to update the propertycountyId
all you have to do is to callhandleChange
: