Recently, I have written about fetching data using Hooks and Render Props. The purpose of that article was to fetch and display data. In this post, I would like to revisit that article and extend it with examples to show how to use the same concept to perform other types of actions (e.g POSTing data).
How do we abstract away data actions?
Whether you are fetching, updating, adding, deleting, or performing custom actions, all these operations have one thing in common. They all go through three stages— loading, success/data, and error. These three stages are building blocks of UI development. Any operation we do (it doesn’t even need to be an API action), it will have these three states.
Now, let’s think about the interface. Our interface accepts an asynchronous action (in our case, it is a function) and return three states with a way to perform the action.
I want to mention, just using a hook or a component is not enough. The actions must respect the provided interface; so that, our logic can work normally. This is one of the important things to remember when abstracting any kind of logic. We should set up interface/contract that all parts of the abstracted idea agree upon.