novafluff
novafluff

Reputation: 911

React is it possible to setState with an function parameter?

Hello i am trying to use a function to set my Modals state and i got alot of modals so what i am doing is trying as this

here is the function call

this.openModal('doneModal')

that goes here

 openModal(state) {
  console.log(state);
  this.setState({state : true}, () => console.log(this.state.doneModal));
}

when i log the parameter state it says doneModal as expected but it does not set the state as the second console.log is still false.

if i change to

this.setState({doneModal:true)} the console log shows true. is it not possible to setState as such?

Upvotes: 0

Views: 146

Answers (2)

Arkej
Arkej

Reputation: 2251

Add square bracket [] to your code:

openModal(state) {
  console.log(state);
  this.setState({ [state]: true}, () => console.log(this.state.doneModal));
}

Upvotes: 2

Shubham Khatri
Shubham Khatri

Reputation: 281686

In order to set the state dynamically you need to wrap your dynamic variable with [] like

openModal(state) {
  console.log(state);
  this.setState({[state] : true}, () => console.log(this.state.doneModal));
}

Upvotes: 1

Related Questions