Learn React redux Thunk with a Project
We have created a React Redux project ealier in this post. But we have made the API call in our component itself, which should have been done in the action creator.
We will enhance our earlier project to do the API call in the action creator, using the middleware of thunk. The code for the earlier part can be take from this github repo.
We will first create an apis folder in the src folder. Inside it create a shopApi.js file. Here, we are using axios to have our baseURL as the fakestorapi.
Now, we will create a new Action creator called FETCH_PRODUCTS in our action-types.js file.
Now, in the productsActions.js file, we will create a new action creator of fetchProducts. Notice, that here we are using axios.get(‘/products’) to get to our complete endpoint.
Next, in our ProductListing.js file we will remove the earlier code of doing an API call and use the fetchProducts action creator.
Now, if we go to http://localhost:3000/ we will get an error that Actions must be plain objects and we should use middleware for async actions.
Now, every API call takes 1–2 seconds and require a middleware like Redux thunk, if we use in the action creator. So, we will first install it through the terminal through the below command.
npm i redux-thunk
Next, we will update the code for store.js file to include the thunk. Notice that we are using composeEnhancers to use the thunk middleware.
Now, we will update the code in productsActions.js to use the dispatch to hit the API endpoint.
Next, we will also add this in our productsReducer.js file.
Now, back in http://localhost:3000/ we are able to get the data again, but this time through Redux Thunk.
Next, we will do the same in our ProductDetails and not do the API call from there. So, first in productsActions.js we will create new function fetchProduct, using our dispatch.
Now, in ProductDetails.js file, we will remove the earlier API call and now use the dispatch to call fetchProduct from the Action creator.
We don’t need to make any changes in the Reducer file, as we are already covering the case. Now, we can select an individual item an it is working fine.
This completes our small post to convert our existing application to use Redux thunk. You can find the code for the same in this github repo.
You can also find this post in video format in this below video.