Last active
September 1, 2023 09:44
-
-
Save ayarushin/69ffd996b2b299254223d83b8b65ec89 to your computer and use it in GitHub Desktop.
Redux hook for creating dispatchers
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 { 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: