Skip to content

Instantly share code, notes, and snippets.

@ayarushin
Last active September 1, 2023 09:44
Show Gist options
  • Save ayarushin/69ffd996b2b299254223d83b8b65ec89 to your computer and use it in GitHub Desktop.
Save ayarushin/69ffd996b2b299254223d83b8b65ec89 to your computer and use it in GitHub Desktop.
Redux hook for creating dispatchers
import { ActionCreator, ThunkAction, bindActionCreators,Action, AnyAction } from "@reduxjs/toolkit";
import { useMemo } from "react";
import { useDispatch } from "react-redux";
type BoundActions<Actions extends Array<ActionCreator<unknown>>> = {
[K in keyof Actions]: (
...args: Parameters<Actions[K]>
) => ReturnType<Actions[K]> extends ThunkAction<infer Return, unknown, unknown, AnyAction>
? Return
: ReturnType<Actions[K]>;
};
export const useActionCreators = <Actions extends Array<ActionCreator<unknown>>>(
...actions: Actions
) => {
const dispatch = useDispatch();
return useMemo(
() => actions.map((action) => bindActionCreators(action, dispatch)) as BoundActions<Actions>,
[]
);
};
declare const myAsyncThunk: (arg: { foo: string }) => ThunkAction<true, any, any, AnyAction>
declare const mySomeSimpleAction: () => Action<string>
// Using example
const [myThunk, mySomeAction] = useActionCreators(myAsyncThunk, mySomeSimpleAction);
myThunk({foo: 'bar'});
mySomeAction();
@ayarushin
Copy link
Author

Example:

const [dispatcher1, dispatcher2, dispatcherN] = useActionCreators(dispatcher1Thunk, slice.actions.dispatcherAction, actionN);

useEffect(() => {
  dispatcherN();
}, []);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment