0

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.

1

1 Answer 1

1

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});
    })
Sign up to request clarification or add additional context in comments.

3 Comments

I am getting error: Error: Objects are not valid as a React child (found: Error: Promise rejected). If you meant to render a collection of children, use an array instead.
Well because error is an object, and you render this.state.name. What you trying to achieve in this.setState({name: error})? You need to render a string in this case like this.setState({name: 'Error'})
@pratteekshaurya Try accepting/upvoting usefull answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.