refactor(useStoreActions): add types
This commit is contained in:
+20
-6
@@ -1,4 +1,4 @@
|
|||||||
import { bindActionCreators, Store } from 'redux';
|
import { bindActionCreators, Store, ActionCreator, ActionCreatorsMapObject } from 'redux';
|
||||||
import {
|
import {
|
||||||
useStore as useStoreRedux,
|
useStore as useStoreRedux,
|
||||||
useSelector,
|
useSelector,
|
||||||
@@ -14,18 +14,32 @@ import { ReactFlowState } from '../types';
|
|||||||
|
|
||||||
export const useTypedSelector: TypedUseSelectorHook<ReactFlowState> = useSelector;
|
export const useTypedSelector: TypedUseSelectorHook<ReactFlowState> = useSelector;
|
||||||
|
|
||||||
export function useActions(actionSelector: (value: any) => any): any {
|
export type ActionCreatorSelector<Action> = (acts: typeof actions) => ActionCreator<Action>;
|
||||||
|
export type ActionMapObjectSelector<Action> = (acts: typeof actions) => ActionCreatorsMapObject<Action>;
|
||||||
|
export type ActionSelector<Action> = (acts: typeof actions) => ActionCreatorsMapObject<Action> | ActionCreator<Action>;
|
||||||
|
|
||||||
|
export function useStoreActions<Action extends ReactFlowAction>(
|
||||||
|
actionSelector: ActionCreatorSelector<Action>
|
||||||
|
): ActionCreator<Action>;
|
||||||
|
|
||||||
|
export function useStoreActions<Action extends ReactFlowAction>(
|
||||||
|
actionSelector: ActionMapObjectSelector<Action>
|
||||||
|
): ActionCreatorsMapObject<Action>;
|
||||||
|
|
||||||
|
export function useStoreActions<Action extends ReactFlowAction>(actionSelector: ActionSelector<Action>) {
|
||||||
const dispatch: ReactFlowDispatch = reduxUseDispatch();
|
const dispatch: ReactFlowDispatch = reduxUseDispatch();
|
||||||
|
const currAction = actionSelector(actions);
|
||||||
|
|
||||||
const action = useMemo(() => {
|
const action = useMemo(() => {
|
||||||
const currAction: any = actionSelector(actions);
|
// this looks weird but required if both ActionSelector and ActionMapObjectSelector are supported
|
||||||
return bindActionCreators(currAction, dispatch);
|
return typeof currAction === 'function'
|
||||||
}, [dispatch, actionSelector]);
|
? bindActionCreators(currAction, dispatch)
|
||||||
|
: bindActionCreators(currAction, dispatch);
|
||||||
|
}, [dispatch, currAction]);
|
||||||
|
|
||||||
return action;
|
return action;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useStoreActions = useActions;
|
|
||||||
export const useStoreState = useTypedSelector;
|
export const useStoreState = useTypedSelector;
|
||||||
export const useStore = (): Store<ReactFlowState, ReactFlowAction> => {
|
export const useStore = (): Store<ReactFlowState, ReactFlowAction> => {
|
||||||
const store = useStoreRedux<ReactFlowState, ReactFlowAction>();
|
const store = useStoreRedux<ReactFlowState, ReactFlowAction>();
|
||||||
|
|||||||
Reference in New Issue
Block a user