Setting up Redux-Thunk in create-react-app

In order to add asynchronous behaviour to redux we use a middleware called redux-thunk.
Just like regular action creator in redux return an action object, redux-thunk action creator return a function. And what special about this function?

It has an argument which we use to dispatch actions based on our async work.

So lets see how we can add redux thunk in our react-app.

Step 1: Create a react app. (npx create-react-app reduxthunk)

Step 2: Install required packages:

Step 3: Create a folder name it we will put all our files related to redux here. I believe you already have redux code up and running. So let’s directly see what changes we have to do in order to make working.

Step 4: Your existing store may look like this:

import { createStore } from “redux”;`import empReducer from “./emoloyee/employeeReducer”;const store = createStore(empReducer);export default store;

Now we have to add two things. Import from redux and import from redux-thunk. So you code will look like this.

import { createStore, applyMiddleware } from “redux”;import thunk from “redux-thunk”;import empReducer from “./emoloyee/employeeReducer”;const store = createStore(empReducer, applyMiddleware(thunk));export default store;

At this point we have added redux thunk in our react app. Now Let’s use async actions.

Step 5: Head back to your action file. And modify it as below.

const getEmployeeData = () => {    return (dispatch) => {        dispatch(updateLoadingStateOfEmpData(true));        setTimeout(() => {            const data = [1, 2, 3, 4, 5];            dispatch(updateEmpData(data));            dispatch(updateLoadingStateOfEmpData(false));        }, 2000);    };};

VOILA, you’re done. :)

Here is the final app for reference:

A passionate iOS Developer since 2014.