Blog>
Snippets

Async Action Throttling Middleware

Provide an example of a middleware that throttles the dispatch of certain async actions, ensuring that they are not called more than once within a specified timeframe to prevent duplicate requests.
const createAsyncActionThrottlingMiddleware = (throttleDuration) => {
  const lastExecuted = {};

  return (store) => (next) => (action) => {
    const currentTime = Date.now();

    // Check if action has 'async' and 'type' properties
    if (!action.async || !action.type) {
      return next(action);
    }

    // Check if we should throttle the action
    if (lastExecuted[action.type] && (currentTime - lastExecuted[action.type]) < throttleDuration) {
      // Do not dispatch the action as it is throttled
      return;
    }

    // Update last executed time for this action type
    lastExecuted[action.type] = currentTime;

    // Dispatch the action
    return next(action);
  };
};
This code defines a factory function that creates an async action throttling middleware for Redux. The middleware checks the time elapsed since the last execution of a particular action type and prevents the action from being dispatched if it is within the specified throttle duration.