Last active
June 6, 2021 14:50
-
-
Save jord-goldberg/658835c211c1527d431ecf7885887141 to your computer and use it in GitHub Desktop.
React-redux batch actions middleware typed using variadic tuples
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 { batch } from 'react-redux'; | |
import { | |
Action, | |
AnyAction, | |
Middleware, | |
ThunkAction, | |
ThunkDispatch, | |
} from '@reduxjs/toolkit'; | |
type MaybeThunkAction<T> = T extends Action | |
? T | |
: T extends ThunkAction<infer R, infer S, infer E, infer A> | |
? ThunkAction<R, S, E, A> | |
: never; | |
type MaybeThunkReturn<T> = T extends Action | |
? T | |
: T extends (...args: never[]) => infer R | |
? R | |
: never; | |
interface BatchDispatch<S, E, A extends Action> extends ThunkDispatch<S, E, A> { | |
<T extends MaybeThunkAction<T[number]>[]>(batchActions: readonly [...T]): { | |
[P in keyof T]: MaybeThunkReturn<T[P]>; | |
}; | |
} | |
type BatchMiddleware< | |
S = {}, | |
A extends Action = AnyAction, | |
E = undefined | |
> = Middleware<BatchDispatch<S, E, A>, S, BatchDispatch<S, E, A>>; | |
/** Should be the first middleware */ | |
export const batchActionsMiddleware: BatchMiddleware = store => next => action => { | |
if (Array.isArray(action)) { | |
let batchedActions; | |
batch(() => { | |
batchedActions = action.map(a => store.dispatch(a)); | |
}); | |
return batchedActions; | |
} | |
return next(action); | |
}; | |
export default batchActionsMiddleware; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment