Problem Summary
I am working on a project where we use a lot of API Requests and we expect that to scale even further with many new endpoints. The project is built using Redux and Hooks. We would like to separate the API requests from the components that's why we are aiming to put everything in redux. However, a problem arises: there is a lot of boilerplate like:
FETCH_DATA_REQUEST, FETCH_DATA_SUCCESS, FETCH_DATA_ERROR
that need to be reproduced for each and every endpoint. Furthermore, we have to handle the loading, success and error for all of them. This seems to be a lot of code especially as the app grows.
What we tried
We tried to create a custom API Hook which uses useReducer
behind the scenes and returns a dynamically generated loading
, success
and error
variables. This hook exposes a sendRequest
method that can be used in the components as such:
sendRequest("GET", `${BASE_URL}/api/endpoint`);
It works well but there is a problem, we are building the API endpoints in the component and that's what we would like to change. That's why we turned to redux.
Ideally we would like to separate the loading and error logic from the reducers and I'm wondering if anyone had an idea (or knows a package) that can help reducing the boilerplate and achieving this goal.