1

Sometimes, in assessments of React projects, I encounter something like this:

export default () => new Promise((resolve, reject) => {
  setTimeout(() => (Math.round(Math.random()) === 0 ? resolve(countries) : reject()), 100);
});

To simulate an API that might or might not have a delay.

My question is, when I want to fetch this promise in a React component, specifically in ComponentDidMount(), what do I need to do to ensure that the render() will wait for this promise to render everything I need? What's the best practice around it?

Thanks!

3
  • I'm not sure what you're asking--render will render as soon as it's called. Components need to be able to render before their data is available, even if it's just an empty render. Or you can await/etc, but that blocks everything, which is generally frowned upon. Jan 15, 2019 at 11:48
  • 2
    Also: To simulate an API that might or might not have a delay. this is not what is being simulated. What is being simulated is a fixed delay after which a promise may or may not encounter an error. To check if your catch errors, presumably.
    – user268396
    Jan 15, 2019 at 11:53
  • You don't need to do anything special. A promise is always asynchronous (delayed), so you just handle it normally with then() and setState().
    – Bergi
    Jan 15, 2019 at 12:43

4 Answers 4

3

This is not specific to a promise that uses random delay or promises at all. Zero-delay setTimeout or instantly resolved promise would produce the same result, though barely visible. The execution of render can't be postponed.

Initial rendering will be performed any way. If component state is changed asynchronously, render should handle initial state correctly:

state = { data: null };

componentDidMount() {
  Promise.resolve('foo').then(data => this.setState({ data }));
}

render() {
  return this.state.data ? (
    <div>{this.state.data}</div>
  ) : (
    'No data'
  );
}
1

You shouldn't need to do anything. The component should still be able to render while waiting for e.g. some state to be populated by the result of the simulated API call. When the promise resolves, if it sets some state on the component then the component will be re-rendered with the new data.

1

You can have a piece of state isLoading in your component that you set to false when the promise has resolved, and use that to render null until then.

Example

const countries = ["gb", "se"];
const getCountries = () =>
  new Promise((resolve, reject) => {
    setTimeout(
      () => (Math.round(Math.random()) === 0 ? resolve(countries) : reject()),
      2000
    );
  });

class App extends React.Component {
  state = { isLoading: true, error: "", countries: [] };

  componentDidMount() {
    getCountries()
      .then(countries => {
        this.setState({ isLoading: false, countries });
      })
      .catch(() => {
        this.setState({ isLoading: false, error: "Fetching countries failed" });
      });
  }

  render() {
    const { isLoading, error, countries } = this.state;

    if (isLoading) {
      return null;
    }
    if (error) {
      return <div>{error}</div>;
    }

    return (
      <div>
        {countries.map(country => (
          <div key={country}>{country}</div>
        ))}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

1

You should store a variable in your state indicated whether or not your promise finished. For that, you can either await your promise and set your state or use .then and set your state in the function's callback.

A minimal code would look like the following :

class MyComponent extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            show: false
        }
    }

    componentDidMount = async () => {
        try {
            await new Promise((resolve, reject) => {
                setTimeout(() => (Math.round(Math.random()) === 0 ? resolve(countries) : reject()), 100);
            });
            this.setState({ show: true })
        } catch(err){

        }
    }

    render = () => this.state.show ? <div>My content</div> : <div/>
}

You can obviously replace the Promise created with the variable you exported and change the rendered component into anything you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.