Async Operation in Redux

Redux Async Data Flow

How data flows in async operation

  1. An event is fired (user clicks a button)

  2. The event handler calls the dispatch() function

  3. The dispatch() function sends the action or thunk (function) to the reducer() function

  4. The middleware intercept the action or thunk so that the action or thunk can't reach the reducer() function directly

  5. The middleware does some work (e.g. fetch data from api)

  6. Our action dispatches and the reducer returns a new state with updated value

  7. The new state is passed to the UI which reflects the changes.

Redux Async Data Flow (Step 1-4)
Redux Async Data Flow (Step 5-6)
Redux Async Data Flow (Step 7)

Handling Async operation in Redux using Middleware

Redux app that uses middleware to fetch data from api and store them in the state.

const { createStore, legacy_createStore, applyMiddleware } = require("redux");
const { delayActionMiddleware, fetchDataMiddleware } = require("./middlewares");

// 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(delayActionMiddleware, fetchDataMiddleware)
);

// subscription
store.subscribe(() => {
  console.log(store.getState());
});

// dispatch actions
store.dispatch({
  type: "added",
  payload: "Learn NodeJs",
});

store.dispatch({
  type: "fetchData",
});

Last updated

Was this helpful?