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!
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 canawait
/etc, but that blocks everything, which is generally frowned upon.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.then()
andsetState()
.