Redux Thunk Middleware
Async operation in Redux using custom Thunk Middleware 
Redux app that uses custom thunk middleware to fetch data from api and store them in the state.
const { createStore, legacy_createStore, applyMiddleware } = require("redux");
const { fetchDataMiddleware } = require("./middlewares");
const { fetchTodoData } = require("./function");
// initial state
const initialState = {
  todos: [],
};
// creating reducers
const todoReducer = (state = initialState, action) => {
  switch (action.type) {
    case "added":
      return {
        ...state,
        todos: [
          ...state.todos,
          {
            title: action.payload,
          },
        ],
      };
    case "loaded":
      return {
        ...state,
        todos: [...state.todos, ...action.payload],
      };
    default:
      break;
  }
};
// creating store
const store = legacy_createStore(
  todoReducer,
  applyMiddleware(fetchDataMiddleware)
);
// subscription
store.subscribe(() => {
  console.log(store.getState());
});
// dispatch the custom function (`fetchTodoData` is called the thunk function)
store.dispatch(fetchTodoData);
const fetch = require("node-fetch");
// Define the delayActionMiddleware as a function that takes the Redux store as a parameter
const fetchDataMiddleware =
  (store) =>
  // Return another function, which is the actual middleware that Redux will invoke
  (next) =>
  // This function takes the next parameter, which represents the next middleware or the final dispatch function
  async (action) => {
    // Check if the action type is a "function"
    if (typeof action === "function") {
      return action(store.dispatch, store.getState); // calls `fetchTodoData` function
    }
    // If the action type is not a function immediately call the next function with the action
    return next(action);
  };
module.exports = {
  fetchDataMiddleware,
};
const fetch = require("node-fetch");
const fetchTodoData = async (dispatch, getState) => {
  const res = await fetch(
    "https://jsonplaceholder.typicode.com/todos?_limit=5" // fetch data from api
  );
  const data = await res.json(); // store data
  // dispatch action to reducer
  dispatch({
    type: "loaded",
    payload: data,
  });
  console.log(`Number of updated todos: ${getState().todos.length}`);
};
module.exports = {
  fetchTodoData,
};
Using 3rd Party Thunk Middleware Package
We can build the same Redux app that using 3rd party thunk middleware
const { legacy_createStore, applyMiddleware } = require("redux");
const { fetchTodoData } = require("./function");
const thunk = require("redux-thunk");
// initial state
const initialState = {
  todos: [],
};
// creating reducers
const todoReducer = (state = initialState, action) => {
  switch (action.type) {
    case "added":
      return {
        ...state,
        todos: [
          ...state.todos,
          {
            title: action.payload,
          },
        ],
      };
    case "loaded":
      return {
        ...state,
        todos: [...state.todos, ...action.payload],
      };
    default:
      break;
  }
};
// creating store
const store = legacy_createStore(todoReducer, applyMiddleware(thunk.default));
// subscription
store.subscribe(() => {
  console.log(store.getState());
});
// dispatch the custom function (`fetchTodoData` is called the thunk function)
store.dispatch(fetchTodoData);
const fetch = require("node-fetch");
// Define the delayActionMiddleware as a function that takes the Redux store as a parameter
const fetchDataMiddleware =
  (store) =>
  // Return another function, which is the actual middleware that Redux will invoke
  (next) =>
  // This function takes the next parameter, which represents the next middleware or the final dispatch function
  async (action) => {
    // Check if the action type is a "function"
    if (typeof action === "function") {
      return action(store.dispatch, store.getState); // calls `fetchTodoData` function
    }
    // If the action type is not a function immediately call the next function with the action
    return next(action);
  };
module.exports = {
  fetchDataMiddleware,
};
const fetch = require("node-fetch");
const fetchTodoData = async (dispatch, getState) => {
  const res = await fetch(
    "https://jsonplaceholder.typicode.com/todos?_limit=5" // fetch data from api
  );
  const data = await res.json(); // store data
  // dispatch action to reducer
  dispatch({
    type: "loaded",
    payload: data,
  });
  console.log(`Number of updated todos: ${getState().todos.length}`);
};
module.exports = {
  fetchTodoData,
};
Last updated
Was this helpful?