keycloak-demo-frontend/src/hooks/useReduxApi.tsx

66 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* eslint-disable no-console */
import { useCallback } from 'react';
import { ThunkAction } from 'redux-thunk';
import { StoreState } from '@Reducers/_InitializeStore/types';
import useDispatch from './useDispatch';
type useReduxAPICallBack = (action: string, props: Array<unknown>) => void;
type actionType =
| 'user'
| 'global'
| 'message';
interface ReduxAction {
[key: string]: (...props: Array<unknown>) => ThunkAction<Promise<void>, StoreState, unknown, { type: string }>;
}
interface ReduxActionModule {
[key: string]: ReduxAction;
}
const VALID_ACTIONS: actionType[] = [
'user',
'global',
'message',
];
const LOAD_MODULE: ReduxActionModule = {};
/**
* 描述 : 取得指定的 Redux Action
*/
export default function useReduxAPI(actionType: actionType): useReduxAPICallBack {
/* Global & Local State */
const dispatch = useDispatch();
/* Main */
return useCallback(
(action: string, props: Array<unknown>) => {
const isInclude = VALID_ACTIONS.includes(actionType);
let reduxType: ReduxAction = {};
if (isInclude) {
if (LOAD_MODULE[actionType]) {
reduxType = LOAD_MODULE[actionType];
} else {
LOAD_MODULE[actionType] = require(`@Reducers/${actionType}/actions`);
reduxType = LOAD_MODULE[actionType];
}
if (reduxType) {
const reduxAction = reduxType[action];
if (reduxAction) {
dispatch(reduxAction(...props));
} else {
console.warn(`Can't find the action ::: ${action}`);
}
} else {
console.warn(`Can't load module ::: ${reduxType}`);
}
} else {
console.warn(`Can't find the action type ::: ${actionType}`);
}
},
[actionType],
);
}