Async ReactJS component.
There are multiple ways to render asynchronous components in React but I wanted to give it a shot on my own by creating a component that is able to listen to an async function and fallback to a temporary render while the component receives a response and triggers a re-render.
I came to this solution by trying to find a more succinct solution to a previous post I created:
I’m using the following timeout helper that executes after a specified time.
// Usage: "async () => await timeout(1000)"
function timeout(time) {
return new Promise((resolve, reject) => {
return setTimeout(resolve, time);
});
}
Now we have our async function:
async function asyncFunction() {
await timeout(1000);
return "Hello World!";
}
And here is my result. This function takes in a promiseFn
which is executed inside a React hook which will trigger a re-render via setState
once there is a response (either success or error) from the asynchronous call.
function RenderAsync({ promiseFn, fallback = null, render }) {
const [state, setState] = React.useState(null);
React.useEffect(() => {
promiseFn()
.then((response) => setState({ response, error: null }))
.catch((error) => setState({ response: null, error }));
}, [promiseFn]);
if (state === null) {
return fallback;
}
return render(state);
}
Pro tip: If you want to avoid an error when the async request resolves after the component unmounts, you can look at: