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

66 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-09-06 10:00:03 +00:00
/* 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],
);
}