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.

pratteek shaurya
  • 850
  • 2
  • 12
  • 34
  • 1
    Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – jonrsharpe Nov 12 '20 at 07:35

1 Answers1

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});
    })
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • 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.` – pratteek shaurya Nov 12 '20 at 07:38
  • 1
    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'})` – Dennis Vash Nov 12 '20 at 07:40
  • @pratteekshaurya Try accepting/upvoting usefull answers – Dennis Vash Nov 12 '20 at 08:51