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);

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);

Last updated

Was this helpful?