Blog>
Snippets

Action Transformation Middleware

Offer a code snippet illustrating a middleware that intercepts particular actions and enriches them with additional data pulled from an external source before they reach the reducers.
const actionTransformationMiddleware = store => next => action => {
  // Check if the action should be enriched
  if (action.type === 'ENRICH_ACTION') {
    // Example of retrieving additional data
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => {
        // Create a new action with the enriched data
        const enrichedAction = {
          ...action,
          payload: {
            ...action.payload,
            additionalData: data
          }
        };
        // Pass the enriched action to the next middleware or reducer
        next(enrichedAction);
      })
      .catch(error => {
        // In case of error, log it and pass the original action
        console.error('Failed to fetch additional data:', error);
        next(action);
      });
  } else {
    // If the action is not to be enriched, pass it as is
    next(action);
  }
};
This middleware intercepts actions of type 'ENRICH_ACTION', fetches additional data from an external API, enriches the action with that data, and then passes the enriched action to the next middleware or the reducer.