Chaining API requests with Redux Thunk

Recently I wanted to be able to gather an array of objects on the first API request, and then for each object, fire off another API request that will get the object data using each object id. As you can imagine, the challenge is chaining multiple API requests using Redux Thunk and Axios in an asynchronous fashion.

Although the problem seemed simple, I realised that the solution is not equally trivial. I also figured out why this kind of design pattern is not documented:

Scenario 1:
Most users don't approach this kind of problem in this manner. In fact, most users just stop at the first API request to render a list of objects. Then they wait for the user to click on one of the objects to render the subsequent object details.

Scenario 2:
Users use other technologies other than Redux Thunk... technologies such as Redux Saga, to chain multiple API requests. In fact, this is one particular use case for which Redux Saga was designed.

Nonetheless, I was convinced that Redux Thunk can be still used. Apart from that, I was in a tight timeline to deliver a project so learning a new technology was out of question. The use case was for a  new aggregator system (from Reddit) that first fires an API to get latest Reddit posts, and then fires another API request for each Reddit postID to get the comments on each post:

I was able to solve this in redux-thunk by making two actions; one to fetch all, and one to fetch each individually. And, to chain them together, we treat each action as a promise (they return axios promises), then let Redux Thunk do its magic.

Let me show you the code snippet:

Notice that I made use of the getState() method to get the array of objects from the first API request promise. The getState() method provides us with a very easy way to pass state values (in this case, the array of objects) to action creators. It is important to understand that we are dealing with promises here, so the getState() method is exactly what we need - once the promise is fulfilled, the second action creator (and therefore, API request) is kicked off.

This design pattern is extremely important and will give you more mileage in your React Redux projects. For posterity, this is how you can then render the data inside your component:

Post a Comment