Barry Michael Doyle Barry Michael Doyle - 1 year ago 239
React JSX Question

React setState not working

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

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

handleSubmit(e) {
const email =
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) {
} else {
// 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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download