When React has become (even more) asynchronous
What’s the thing you miss the most in React ? async render() is probably one, guess what? it’s coming and you can already play with it!
When we have to deal with data we used to separate data fetching from rendering. One definition of React itself could have been “react to state changes”.
What if we now just have to worry about reacting to user actions? and have everything related to fetching wrapped up in a new render() with superpowers ?
The naive way
It could be great if render was just an async function (the one introduced in ES2017).
It seems to solve everything, right? in reality it doesn’t, the main problem is that you’re fetching data at every render 💰. It will probably not be really slow at first, because your browser caches the request but it’s definitely bad.
Let me introduce simple-cache-provider …
The resource call will return the data directly if it’s cached, if not it will throw a promise which will suspend our rendering. If you try this code you will have a little problem.
Oops, we’ve broken everything, the thrown promise need to be catched with something like mega <ErrorBoundary /> and … there is a component for that™: <Timeout />. 99% of the magic is inside this component. It is responsible for suspending rendering and it will display <Fallback /> as soon as the delay (ms) expires if the promise is not resolved yet.
Now we have to implement error catching, let’s do it !
We could have something like this. The implementation starts to be heavy, what if we have everything above packed up and available with a sexy syntax ? I have a gift for you. 🎅
It’s the missing ultra-thin layer to play with suspense and keep a great developer experience, with something similar to the Relay API. 😎
That’s it, and the real life example at CodeSandbox:
You can explore the source code of drum-roll here, it’s available at npm through the next tag 🚀
yarn add drum-roll@next
For the time being create-react-app will show up react-error-overlay when an error throw, not your fallback error component, don’t worry this will change soon.
🚨 Everything here is experimental and shouldn’t be used in production !
If you don’t want to miss any of my articles, follow me on twitter @DidierFranc