Home > Enterprise >  How to use the UseState hook as the name of a property in an object?
How to use the UseState hook as the name of a property in an object?

Time:12-31

In my project, i want to make an axios post request.

I want that if the useState hook is set to true, the name of the property is different, than if it is set to false.

For example:

const [state, setState] = useState(); //like useEmail

const object ={
property1 like name: someProperty,                      //like name value
property2 like email/phonenumber: someOtherproperty    //like email/phonenumber value
}

setState(true)// object property2 = email
setState(false)//object property2 = number

Is it possible? Thanks for your help!

CodePudding user response:

const [state, setState] = useState(false);

const object = {
  [state ? 'email' : 'name']: 'something'
}
  • Related