Redux Thunk
builtbyjosh
Posted on June 12, 2021
What is thunk? Thunk is one of the most common redux middleware packages for redux. What is middleware? Middleware has the ability to stop, modify, or otherwise mess around with actions. There are plenty of middleware packages available, and they are mostly used for dealing with async actions. That is where thunk comes into play!
It is mainly used for asynchronous data calls. You can delay the dispatch of an action until all of the desired data is retrieved or the returned function has been called and completed its task. An example would be making a GET request to an outside API, you will need to wait for all of the data to be returned before you dispatch the action associated with the request. Or else you will run into errors when trying to render your components.
Normally, action creators can only return objects. But with redux-thunk, they can return functions to the action creators. When a normal object is passed to the action creator, it will carry out the action right away. But if a function, ie a fetch to an outside API, is called, thunk will call that function asynchronously. Once the promise is resolved, thunk will pass the returned value to the action creator.
The main way to use redux-thunk is to apply it when your redux store is created. You will first need to install redux-thunk to your app by using the command:
npm install --save redux-thunk
Once thunk is installed, you will need to import it into your app. As well as importing createStore and applyMiddleware from the redux package.
import { createStore, applyMiddleware } from 'redux
import thunk from 'redux-thunk';
Once all of these files are imported into your component, you will be able to create your redux store using:
const store = createStore(
yourReducer,
applyMiddleware(thunk)
):
Make sure to import your reducer to the file where you are creating your store. This will connect your store and reducers to thunk and allow you to make asynchronous calls.
Posted on June 12, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.