From 1f7d20da1bfb92c7fef931d5d99563cbde3c693f Mon Sep 17 00:00:00 2001 From: moklick Date: Thu, 11 Feb 2021 15:28:36 +0100 Subject: [PATCH] refactor(useStoreActions): add types --- src/store/hooks.ts | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/store/hooks.ts b/src/store/hooks.ts index 4deb9b10..4ee7affc 100644 --- a/src/store/hooks.ts +++ b/src/store/hooks.ts @@ -1,4 +1,4 @@ -import { bindActionCreators, Store } from 'redux'; +import { bindActionCreators, Store, ActionCreator, ActionCreatorsMapObject } from 'redux'; import { useStore as useStoreRedux, useSelector, @@ -14,18 +14,32 @@ import { ReactFlowState } from '../types'; export const useTypedSelector: TypedUseSelectorHook = useSelector; -export function useActions(actionSelector: (value: any) => any): any { +export type ActionCreatorSelector = (acts: typeof actions) => ActionCreator; +export type ActionMapObjectSelector = (acts: typeof actions) => ActionCreatorsMapObject; +export type ActionSelector = (acts: typeof actions) => ActionCreatorsMapObject | ActionCreator; + +export function useStoreActions( + actionSelector: ActionCreatorSelector +): ActionCreator; + +export function useStoreActions( + actionSelector: ActionMapObjectSelector +): ActionCreatorsMapObject; + +export function useStoreActions(actionSelector: ActionSelector) { const dispatch: ReactFlowDispatch = reduxUseDispatch(); + const currAction = actionSelector(actions); const action = useMemo(() => { - const currAction: any = actionSelector(actions); - return bindActionCreators(currAction, dispatch); - }, [dispatch, actionSelector]); + // this looks weird but required if both ActionSelector and ActionMapObjectSelector are supported + return typeof currAction === 'function' + ? bindActionCreators(currAction, dispatch) + : bindActionCreators(currAction, dispatch); + }, [dispatch, currAction]); return action; } -export const useStoreActions = useActions; export const useStoreState = useTypedSelector; export const useStore = (): Store => { const store = useStoreRedux();