React: Fetching from an API using Redux and Thunk

Angelo Urtula
2 min readFeb 1, 2022

When building a React App that relies on using an API for saving and displaying data, more likely than not you’ll be using Thunk, as asynchronous requests to APIs are the most common use of Thunk in React. The first thing you’ll need to do is make sure you have Thunk installed in your app, so in your app’s frontend directory (your folder containing your React app), use the command:

“npm install redux-thunk”

Thunk can then be imported to your index.js for its initial setup with createStore.

As an example, here is the index for my Mod 5 Flatiron Project: redthat. Line 9 shows us importing thunk, while line 14 shows us passing thunk as an argument for applyMiddleware(). With this, Thunk has been configured and we can begin using it in our code, i.e. to make fetch requests. So what exactly does Thunk allow us to do? For one, it allows our action creators to return a function instead of an action object. This opens up a lot of versatility, allowing Thunk to do things like delaying dispatching of actions under certain conditions or until a condition is met. That being said, you could write conditionals for dispatching actions, as an example. For the purpose of this project, however, Thunk is used to handle asynchronous requests to my Rails API and then taking the response and using it to dispatch data to my Redux store.

Here, you can see my action creator returning a function instead of an object! After asynchronously fetching the posts data from my API, the function takes that data and uses it to dispatch an update to our Redux store, filling it with all of the posts from the API.

So how is this action creator function utilized elsewhere? As seen above, we first need to import our new fetchPosts function (line 4). We then pass that fetchPosts() function as an argument for dispatch(), assigning it to a function that’s being passed down to PostContainer as a prop (line 29). This then allows us to control when the fetch is made by placing the now prop function within something like componentDidMount(), meaning the data will be fetched when PostsContainer mounts!

--

--