Laxe96
Laxe96

Reputation: 41

Unexpacted Promise Pending in React.js

I'm not understanding at all why I get this problem. With the first console.log in Parent, I verified output is correct and Promise is definitely resolved. But when I try to display state contenent in Child I see this:

Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(5)

Even if PromiseValue is correct the Promise is pending, although in Parent it's viewed like Resolved. How could this be possible?

Parent Code:

....
....
....
getElements = async () => {


const elems = await API.askForElements();
console.log(elems) // --> The output is correct!

return elems;
 };


render() {


return (
     <div className="App">
     <Child elemenets={this.getElements()}/>
     </div>
     ); 
     }
    }

Child Code:

class Child extends React.Component {

 state = {

 elements: this.props.elements
 
 }

 render(){

 console.log(this.state.elements); // It return promise {<pending>}


 ....

Upvotes: 1

Views: 1797

Answers (1)

F&#225;bio Batista
F&#225;bio Batista

Reputation: 25280

You'll have to wait until the promise is resolved. Here's one way to do it, without changing much of your code:

class Child extends React.Component {
  state = { elements: null, error: null }

  componentDidMount() {
    this.props.elements
      .then(elements => this.setState({ elements }))
      .catch(e => this.setState({ error }));
  }

  render() {
    console.log(this.state.error);
    console.log(this.state.elements);

In that example, the props.elements is (and will always be) just a Promise. When that promise is resolved, the state will be set with the resolved value (or error).

Make sure you handle the 3 possible states:

  • Promise is still pending (both state.elements and state.error are null);
  • Promise is resolved (state.elements is not null); and
  • Promise is rejected (state.error is not null).

Upvotes: 0

Related Questions