Simran Mhaske
Simran Mhaske

Reputation: 65

Why my state is not getting updated even after writing the setState method?

import React, { Component } from 'react'

class Columns extends Component{ constructor(props){ super(props)

    this.state={
        message:'Hello'
    }
}

changeMessage(){
    
     this.setState=({
         message:'Welcome'
    })
}

render(){
    return(
        <div>
            <div>{this.state.message}</div>
            <button onClick={this.changeMessage}>Click</button>
        </div>
    )
}

} export default Columns

Upvotes: 2

Views: 155

Answers (2)

ray
ray

Reputation: 27285

Because passing it as this.changeMessage detaches it from the component scope. When the button invokes it, "this" is no longer the component.

Change it to an arrow function: () => this.changeMessage()

I've tried to explain this scope issue in another answer in the past if you want the details.

Also, as Aaron points out you also have an extraneous = in your changeMessage handler.

Upvotes: 3

Aaron
Aaron

Reputation: 2237

As ray hatfield said above, you're losing the this context and need to use an arrow function, but also you're not calling setState; you're overriding it.

Remove the = from

this.setState=({
     message:'Welcome'
})

so that it says:

this.setState({
    message:'Welcome'
})

Upvotes: 5

Related Questions