Using the Redux Thunk to Dispatch Async Actions with React

John Au-Yeung
4 min readApr 26, 2020
Photo by Pietro Mattia on Unsplash

With Redux, we can use it to store data in a central location in our JavaScript app. It can work alone and it’s also a popular state management solution for React apps when combined with React-Redux.

In this article, we’ll look at how to use React Redux and Redux Thunk to dispatch async actions in a React app.

Installation

Redux Thunk is available with the redux-thunk package. To install it, we run:

npm install redux-thunk

Usage

We can use it by using the applyMiddleware function to apply the thunk middleware from redux-thunk .

For example, we can use it as follows:

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import { Provider, useSelector, useDispatch } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
function joke(state = {}, action) {
switch (action.type) {
case "SET_JOKE":
return { ...action.joke };
default:
return state;
}
}
const store = createStore(joke, applyMiddleware(thunk));const fetchJoke = () => {
return async dispatch => {
const response = await…

--

--