Search code examples
reactjssetstate

Dynamically setting state object by passing it as variable name : React


I have this scenario where I need to send a list of state object variables, and then dynamically set them inside the setState function by using the passed variable. Trying to achieve the same. I am maintaining one setState functions, to which I will be passing state variables which are then set accordingly.

Am I going somewhere wrong?

Help would be appreciated.

Relevant snippet has been posted

constructor()
{
  super(props);
  this.state ={
      val1 : '',
      val2: '',
      val3: '',
  }
}

fetchValues = (stateVariable) =>{  // here the stateVariable ie val1,val2,val3 will be passed . 

  //fetching a value that will be set to the state object variables   
   this.set(stateVariable,value)
}

set = (val) => {
 this.setState(`${val}`: val
}

Solution

  • You can do that this way:

    const set = val => {
      this.setState({ [val]: val });
    };
    

    Plus you had issues like:

    • There's no => after (val).
    • The closing braces aren't right.
    • You're missing a const.

    Fixed everything for you.

    Quick demo for you.

    var val = "Praveen";
    
    console.log({ [val]: val });