Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not mutate state directly. Use setState() react/no-direct-mutation-state

I have this code:

constructor(props) {
    super(props)
    this.state = {
        loginButton: '',
        benchmarkList: ''
    }
    if (props.username == null) {
        this.state.loginButton = <GoogleButton></GoogleButton>
    } else {

    }
}

It is giving me an ESLint warning:

Do not mutate state directly. Use setState() react/no-direct-mutation-state.

Now what am I supposed to do as I can't use setState inside constructor directly as it creates error and updating like this gives me error.

like image 775
Jenna Wesley Avatar asked Jun 16 '17 14:06

Jenna Wesley


2 Answers

First of all, we should not store the ui components inside state variable, state should contain only data. All the ui part should be inside render method.

If you want to render some component on the basis of any data then use conditional rendering. Check the value of this.state.loginButton and if it is null then render that button.

Like this:

constructor(props) {
    super(props)
    this.state = {
        loginButton: props.username,
        benchmarkList: ''
    }
}

render(){
    return(
        <div>
            {!this.state.loginButton ? <GoogleButton></GoogleButton> : null}
        </div>
    )
}

Ideally we should not store the props value in state also, so directly use this.props.username, i did that because don't know about the complete code.

like image 63
Mayank Shukla Avatar answered Oct 17 '22 14:10

Mayank Shukla


constructor(props) {
    super(props)
    this.state = {
      loginButton: props.username == null? <GoogleButton></GoogleButton>: '',
      benchmarkList: ''
    }
  }

Or You can use setState in componentWillMount()

componentWillMount(){
   let loginButton = props.username == null? <GoogleButton></GoogleButton>: '';
   this.setState({loginButton: loginButton});
}
like image 25
Andrew Avatar answered Oct 17 '22 14:10

Andrew