Organizing fetches in redux actions
This article assumes that you are:
- Using redux and redux thunk
- Using fetch API for making API requests
- Using jwt tokens stored in localStorage for authorization with the external api server
If you’ve been working with external CRUD-like apis then your actionCreators would probably look something like this:
|
|
To allow the client to perform simple CRUD tasks for a single resource, we can see that already a lot of code is being repetitive. Especially the fetch
-ing part. Imagine making actions for several endpoints (such as comments, feeds, contacts …)
In order to tidy up these fetch calls, I’ll make a ApiClient class that has the following signature:
|
|
where methods
specify which methods are allowed by the endpoint.
Then, we could use it like this inside our actionCreators
|
|
The internals of the ApiClient class might look something like this
|
|