skip to Main Content

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


  1. 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 });
    
    Login or Signup to reply.
  2. I tried to update some field(countryID) using other functions

    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 property countyId all you have to do is to call handleChange :

    handleChange({target:{name: "countyId", value: 130}})
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search