Let Me Tink About It
Let Me Tink About It

Reputation: 16122

Loading async data into React component

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?

Upvotes: 1

Views: 4358

Answers (1)

Teneff
Teneff

Reputation: 32158

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

Upvotes: 3

Related Questions