1

I need to asynchronously load external data into my React component. The documentation here provides the following code example.

// After
class ExampleComponent extends React.Component {
  state = {
    externalData: null,
  };

  componentDidMount() {
    this._asyncRequest = loadMyAsyncData().then(
      externalData => {
        this._asyncRequest = null;
        this.setState({externalData});
      }
    );
  }

  componentWillUnmount() {
    if (this._asyncRequest) {
      this._asyncRequest.cancel();
    }
  }

  render() {
    if (this.state.externalData === null) {
      // Render loading state ...
    } else {
      // Render real UI ...
    }
  }
}

But what might loadMyAsyncData() look like to make it "thenable?" I would imagine it might use async/await?

Can someone provide an example?

1
  • It would just be a function that returns a promise, and inside the promise you have an API call that resolves/rejects the promise based on the API response. Commented Mar 10, 2019 at 23:10

1 Answer 1

3

To be "thenable loadMyAsyncData should return a Promise.

Here's an example loadMyAsyncData returning a promise and using setTimeout to delay resolving the promise after 1 second

const loadMyAsyncData = () => new Promise((resolve, reject) => {
  setTimeout(() => resolve({
    example: "value"
  }), 1000)
})

you can use the code above this._asyncRequest = loadMyAsyncData().then( ..... ) or use async/await instead

async componentDidMount() {
  this._asyncRequest = loadMyAsyncData()
  const externalData = await this._asyncRequest;
  this._asyncRequest = null;
  this.setState({externalData});
}

codesandbox example

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. +1. I really appreciate the codesandbox example. Quick question. Is there any way to use async/await to define loadMyAsyncData() or does it have to use the new Promise() syntax?
@Mowzer it depends on the implementation, but in this case we need use new Promise()
Is that because it needs to return a promise? And async/await does not return a promise?

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.