Created
May 26, 2021 09:50
-
-
Save n3dst4/ae0901601e5c8ce69843d87bb4f75195 to your computer and use it in GitHub Desktop.
redux debounce middleware
This file contains 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 { Dispatch } from "react"; | |
import { AnyAction, Store } from "redux"; | |
import { State } from "./types"; | |
/** | |
* Create a middleware that will debounce actions of a given kind. | |
* | |
* Debouncing means that if a certain action happens more than once in a given | |
* period, only the last one will actually take effect. | |
*/ | |
export default ( | |
actionType: string, | |
delay: number, | |
) => ( | |
_: Store<State>, | |
) => { | |
let timeout: any; | |
return (next: Dispatch<AnyAction>) => (action: AnyAction) => { | |
if (action.type === actionType) { | |
clearTimeout(timeout); | |
timeout = setTimeout(() => { next(action); }, delay); | |
} else { | |
return next(action); | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment