Skip to content

Instantly share code, notes, and snippets.

@brentmulligan
Last active November 5, 2019 21:01
Show Gist options
  • Save brentmulligan/21922996bd9a46dfd611a3dd314b6942 to your computer and use it in GitHub Desktop.
Save brentmulligan/21922996bd9a46dfd611a3dd314b6942 to your computer and use it in GitHub Desktop.
debounce redux form actions with redux batched actions
import debounce from 'lodash/debounce'
import { batchActions } from 'redux-batched-actions'
/**
* Create a redux middleware function that debounces specified
* action types and processes them together with batchActions.
*
* @param {array} actionTypes - An array of actions types to debounce
* @param {number} [wait=0] - Time to wait before executing action batch
* @returns {function} - middleware function
*/
export default (actionTypes, wait = 0) => {
const actionQueue = {}
const debouncedDispatch = {}
const DEBOUNCE_ACTION = {}
const dispatch = (store, key) => {
store.dispatch(batchActions(actionQueue[key]))
actionQueue[key] = []
}
const debounceAction = (store, action) => {
actionQueue[action.type].push(action)
return debouncedDispatch[action.type](store, action.type)
}
actionTypes.forEach((type) => {
DEBOUNCE_ACTION[type] = true
actionQueue[type] = []
debouncedDispatch[type] = debounce(dispatch, wait)
})
return (store) => next => action => (
DEBOUNCE_ACTION[action.type] ? debounceAction(store, action) : next(action)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment