Update a array out side handlechange function React JS

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;
      [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

>Solution :

This syntax:

[name]: value

uses the value of the variable name as the object key. So, for example, if name has the value "foo" then it creates or updates the key foo to the value of value:

foo: 'some value'

So, when you use this same syntax:

[values.countryId]: 130

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 called 100 and giving it the value 130:

100: 130

If you want to explicitly update the field countryId, just use countryId:

countryId: 130

So the whole line would be:

SetValues({ ...values, countryId: 130 });

Leave a Reply