pratteek shaurya
pratteek shaurya

Reputation: 960

Implementing promise in react

I am trying to implement simple promise is react.

below is my code:

import React, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
    };
  }
  componentWillMount() {
    var promise = new Promise( (resolve, reject) => {
   
     let name = 'Shubham'
   
     if (name === 'Shubham') {
      resolve("Promise resolved successfully");
     }
     else {
      reject(Error("Promise rejected"));
     }
    });
   
    promise.then( result => {
     this.setState({name: result});
    }, function(error) {
     this.setState({name: error});
    });
   }
   render() {
    return (
     <div className="App">
      <h1>Hello World</h1>
      <h2>{this.state.name}</h2>
     </div>
    );
   }
}
export default App;

This works as long as the name matches. If I change let name = 'Shubham' to let name = 'Shaurya' then it is giving me error Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined. I am not able to understand what error am I doing.

Upvotes: 0

Views: 49

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53984

In your promise error handler, this refers to function instance and not to the class component's. Change it to an arrow function:

promise.then( result => {
    ...
    }, (error) => {
     this.setState({name: error});
    })

Upvotes: 1

Related Questions