Jenna Wesley
Jenna Wesley

Reputation: 95

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.

Upvotes: 9

Views: 14226

Answers (4)

Bulka
Bulka

Reputation: 159

just add setState

if (props.username == null) {

       this.setState({
            loginButton: <GoogleButton></GoogleButton>
       })

} else {


Upvotes: 0

Mayank Shukla
Mayank Shukla

Reputation: 104369

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.

Upvotes: 8

oklas
oklas

Reputation: 8220

How to update state inside constructor in ReactJS?

Create the data struct, modify it as need, and assign to state at the end when all is done:

constructor(props) {
    super(props)
    let state = {
        loginButton: '',
        benchmarkList: ''
    }
    if (props.username == null) {
        state.loginButton = true
    } else {
        state.loginButton = false
    }
    this.state = state
}

Upvotes: 0

Andrii Starusiev
Andrii Starusiev

Reputation: 7764

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

Upvotes: 4

Related Questions