0

I am trying to set variable in this.state

My variable is defined as VariableName+"Error"

This code works well, but it isnt good to mutate state directly:

this.state[VariableName+"Error"] = "";

My bad try to mutate state in this.state which does not work:

this.setState({
      VariableNameError: ""
  })
Bobek
  • 757
  • 3
  • 7
  • 15
  • 1
    `this.setState({ [VariableName+"Error"]: '' })` – Mayank Shukla Jun 29 '18 at 07:48
  • @MayankShukla Doesnt work for me – Bobek Jun 29 '18 at 08:01
  • can you show exactly what u r trying? – Mayank Shukla Jun 29 '18 at 08:07
  • this.state.validationRules.map((rule, i) =>{ var propertyName = rule["a:PropertyName"][0]; this.setState({ [propertyName+"Error"]: "" }) In propertyName is string with VariableName – Bobek Jun 29 '18 at 08:09
  • 'a:PropertyName' is fixed string or `PropertyName` is a variable there? – Mayank Shukla Jun 29 '18 at 08:21
  • It is string. thank you @MayankShukla you have solved this. I didnt know that if i once use set.state i cant mutate directly in next code. – Bobek Jun 29 '18 at 08:25
  • check this answer for more details about [**async nature of setState**](https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately/42593250#42593250), also better to not use setState in loop, write it like this: `let obj = {}; this.state.validationRules.forEach((rule, i) => { var propertyName = rule["a:PropertyName"][0]; obj[propertyName+'Error'] = ''; }) this.setState(obj) ;` – Mayank Shukla Jun 29 '18 at 08:29

0 Answers0