Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading