Skip to content

Instantly share code, notes, and snippets.

@jord-goldberg
Last active June 6, 2021 14:50
Show Gist options
  • Save jord-goldberg/658835c211c1527d431ecf7885887141 to your computer and use it in GitHub Desktop.
Save jord-goldberg/658835c211c1527d431ecf7885887141 to your computer and use it in GitHub Desktop.
React-redux batch actions middleware typed using variadic tuples
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