From Ember to React — Part 2: Top-Level component concerns
In Part 1 of “From Ember to React” series I introduced a pattern to re-use data fetched in a Top-Level component into his children. Then I started to realize that I could make use of this pattern to bring even more ideas from Ember into React! Here are a couple I used lately:
Sometimes we want to show a “Loading indicator” to let the users know when a request is being processed. As suggested by this post, logic and markup should be placed on a top-level component to be reused by subsequent components.
As before, I remembered a handy Ember feature called Loading / Error Substates already baked into the framework itself. Turns out our previous “High-order Component & Wrapper”-pattern is a perfect place to replicate this pattern, as we don’t need to repeat the loader in every single component:
This way we can re-use the Loader logic in children components in case we need to hit another remote API:
We can apply a similar pattern for error handling, in this case I would use a generic modal to show potential Network errors:
And you can use it within the children components in similar fashion using a
*Update: I found it’s also a good idea to put Error Boundaries logic around here as well
Nothing is perfect…
The downside (no pun intended) to this patterns is that we need to pass down the actions props (
showErrorModal) to every child component, and if our component tree is deep enough that’d be a tedious and error-prone task, not to mention super verbose!
The solution for this problem in Ember was using an add-on called ember-route-action-helper, which is used to “bubble up” actions to the parent route. This is possible due to the existential difference between Routes and Components in Ember’s object model, but since React is all about Components-only we cannot easily replicate this feature…or can we? 🤔
When Context API?
Most of this pitfalls could potentially be alleviated using the React Context API, but again, I will leave that for another day 😬
How to fetch data in React - RWieruch
Do you want to go beyond a static React application? Then it's about time to fetch data from a third party API. This…
Loading / Error Substates - Routing - Ember Guides
The Ember Router allows you to provide feedback that a route is loading, as well as when an error occurs in loading a…