Last active
November 5, 2019 21:01
-
-
Save brentmulligan/21922996bd9a46dfd611a3dd314b6942 to your computer and use it in GitHub Desktop.
debounce redux form actions with redux batched actions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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