1

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
}

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.