Barry Michael Doyle Barry Michael Doyle - 1 month ago 19
React JSX Question

React setState not working

I have the following constructor and function in a react component that I've created.

constructor() {
super()
this.state = {
error: false
}
}

handleSubmit(e) {
e.preventDefault()
const email = this.refs.email.value
const password = this.refs.password.value
const self = this

firebase.auth().signInWithEmailAndPassword(email, password).then(
function(result) {
const location = self.props.location
if (location.state && location.state.nextPathname) {
self.context.router.replace(location.state.nextPathname)
} else {
self.context.router.replace("/home")
}
// User signed in!
console.log("User signed in!")
}).catch(function(error) {
this.setState({error: error}) // Error points to this line
})
}


I keep getting the following error in the console:


Uncaught TypeError: Cannot read property 'setState' of undefined


Can anyone help my identify the problem?

Answer

In the following code, you use 'this', when you should be using 'self'

catch(function(error) {
    this.setState({error: error}) // Error points to this line
})

should be

catch(function(error) {
    self.setState({error: error}) // Error points to this line
})
Comments