Blog>
Snippets

Middleware for Asynchronous Data Persistence

Illustrate the integration of middleware to handle side effects such as persisting course progress to a server or loading course content asynchronously.
// Define an async persistence middleware function
const asyncDataPersistenceMiddleware = store => next => action => {
  if (action.type === 'PERSIST_COURSE_PROGRESS') {
    // Perform the asynchronous persistence (e.g., API call)
    saveCourseProgress(action.payload).then(
      response => store.dispatch({ type: 'COURSE_PROGRESS_SAVED', payload: response }),
      error => store.dispatch({ type: 'COURSE_PROGRESS_SAVE_FAILED', payload: error })
    );
  } else if (action.type === 'LOAD_COURSE_CONTENT') {
    // Perform the asynchronous content loading
    loadCourseContent(action.payload).then(
      content => store.dispatch({ type: 'COURSE_CONTENT_LOADED', payload: content }),
      error => store.dispatch({ type: 'COURSE_CONTENT_LOAD_FAILED', payload: error })
    );
  }

  // Continue to the next middleware
  return next(action);
}
This middleware intercepts actions related to course progress persistence and course content loading. For the relevant actions, it performs the respective asynchronous operations and dispatches new actions based on the results (success or error).
// Function to save course progress to the server
async function saveCourseProgress(progress) {
  // API call to persist course progress
  // Return a Promise that resolves or rejects based on the API response
  return fetch('/api/save-progress', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(progress)
  }).then(response => response.json());
}
Function to asynchronously save course progress to the server. It returns a Promise that will be handled by the middleware.
// Function to load course content from the server
async function loadCourseContent(courseId) {
  // API call to load course content
  // Return a Promise that resolves or rejects based on the API response
  return fetch(`/api/load-content/${courseId}`).then(response => response.json());
}
Function to asynchronously load course content from the server. It returns a Promise that the middleware will handle.
// Example of applying the middleware to the Redux store
import { applyMiddleware, createStore } from 'redux';
import rootReducer from './reducers';

// Create the Redux store and apply the middleware
const store = createStore(
  rootReducer,
  applyMiddleware(asyncDataPersistenceMiddleware)
);
Example of how to apply the previously defined async persistence middleware to the Redux store using 'applyMiddleware' from Redux.