Pejman Nik

@pejmanNik

ANOTHER way to call restful API in Redux

Announcing a general way to make developer life easier for calling API in React-Redux.

Photo by Randy Fath on Unsplash

Recently, I’ve switched from backend development to the frontend side. in first sight, I found API call is truly tough.

Why we need to make a type + action + take action (redux-saga)+ handler function 😐 for each API call?? and again a type + action + reducer to store the result. I keep asking my self.

I do a lot of research and all sample and document are the same way more and less. like this example:

So I think to the other way, something more functional.

API Client

API client is a structure to handle the most API call in one place without duplicate codes (DRY). I’ll explain this structure using redux middleware but you can implement it in your way. Even in another middleware library like Tunk or Saga. As you can see the explanation is so simple and straightforward. I try to make it easy to understand

Implementation

API Request is our base API class. you can define it like this:

I use Carbon to generate this images for code snips. you can see full implementation in my GitHub.

Whenever you want to call an API you need just create an instance of this class and dispatch this action to redux.

We can create an action function:

By using this function we can also use call API directly in a Promise (if it needed).

For the response, we can define APIResponse class:

Now we need to handle the request and complete the puzzle. The redux middleware (I use Axios to sending the request):

How to Use it?

Calling API can’t be easier than it 😎 like the general way we can use redux connect in the component to send a request and receive a response.

How to Customize?

You may think of some specific scenarios and how you can handle it with this structure. What solves my problem was this tow powerful option:

Option

With options. You can define an options object as you need. Something like this

You can define an option for save response in store or show a message after the operation and anything based on your need.

Middleware

The other thing can give you more control is middleware. If the option is not enough for your need you can define middleware interface like this:

Now implement this interface and add it to request object to get full control over request flow.

We need to change APIRequest class to support option and middleware.

Beyond

You can even make it better. for example with this structure, you can easily handle all changes in local store to avoid duplication. More specifically you can implement a flow to delete the record from the local store after sending DELETE request In general.

As I mentioned before I want just to give you an idea about what am I means. if you are interesting you can see a full demo in GitHub:

Topics of interest

More Related Stories