Trying to implement a SIMPLE promise in Reactjs Trying to implement a SIMPLE promise in Reactjs reactjs reactjs

Trying to implement a SIMPLE promise in Reactjs


You are using React in a wrong way. A Promise is designed to return result at a later point of time. By the time your promise has been resolved or rejected, your render would have finished execution and it wont update when the promise completes.

render method should only depend on props and/or state to render the desired output. Any change to prop or state would re-render your component.

  • First, identify where your Promise should go in the life cycle of the component(here)
  • In your case i would do the following

    • Initialize an state inside your constructor(ES6) or via getInitialState

      constructor(props) {  super(props);  this.state = {    name: '',  };}
    • Then on componentWillMount or componentDidMount which ever suits you, call the promise there

      componentWillMount() { var promise = new Promise( (resolve, reject) => {  let name = 'Paul'  if (name === 'Paul') {   resolve("Promise resolved successfully");  }  else {   reject(Error("Promise rejected"));  } }); let obj = {newName: ''}; promise.then( result => {  this.setState({name: result}); }, function(error) {  this.setState({name: error}); });}
    • Then in render method write something similar to this.

      render() { return (  <div className="App">   <h1>Hello World</h1>   <h2>{this.state.name}</h2>  </div> );}


You need to be thinking about the scope you're in. When you are in the function you're passing to promise.then, you are in a new block scope and therefore any var you create in the function won't exist outside of it's scope. I'm not sure how you're defining your React components, but assuming you have a newName variable on your component, there are two ways you could solve the scope problem - bind and arrow functions:

promise.then(function(result) {  this.newName = result; //or what you want to assign it to}.bind(this))

and then you could reference it using {this.newName}

Or with an arrow function:

promise.then((result) => {  this.newName = result; //or what you want to assign it to}.bind(this))

I would recommend watching this egghead video to help you understand the this keyword in javascript.