Blog>
Snippets

Action Debouncing Middleware

Illustrate the creation of middleware that debounces certain actions, ensuring that they are only dispatched if a specified period has elapsed since the last dispatched action of the same type.
function createDebounceMiddleware() {
  let timer = {};
  return store => next => action => {
    const { meta } = action;
    if (meta && meta.debounce) {
      const { time, key } = meta.debounce;
      if (timer[key]) clearTimeout(timer[key]);
      timer[key] = setTimeout(() => {
        next(action);
      }, time);
    } else {
      next(action);
    }
  };
}
This code snippet creates a debounce middleware for Redux. It checks if the dispatched action contains a 'debounce' meta field. If it does, the middleware delays the action dispatch by the specified time, ensuring that only the last action in a rapid sequence is dispatched. Actions without the 'debounce' meta field pass through immediately.
const { applyMiddleware, createStore } = require('redux');
const rootReducer = (state = {}, action) => state;
const debounceMiddleware = createDebounceMiddleware();
const store = createStore(rootReducer, applyMiddleware(debounceMiddleware));
Here we import necessary functions from Redux, define a root reducer as a placeholder, create an instance of the debounce middleware, and finally create the Redux store applying the debounce middleware. This setup initializes the store with the debounce capability.
store.dispatch({ type: 'ACTION_TYPE', meta: { debounce: { time: 300, key: 'uniqueActionKey' } } });
This code dispatches an action through the store that includes a 'debounce' meta field. The 'time' property specifies the delay in milliseconds, and the 'key' property provides a unique identifier to group actions of the same type for debouncing.