-
Notifications
You must be signed in to change notification settings - Fork 0
/
DynamicModuleLoader.tsx
52 lines (43 loc) · 1.61 KB
/
DynamicModuleLoader.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { Reducer } from '@reduxjs/toolkit';
import {
IReduxStoreWithManager,
IStateSchema,
TStateSchemaKey,
} from '@/app/providers/StoreProvider';
import { ReactNode, useEffect } from 'react';
import { useDispatch, useStore } from 'react-redux';
export type TReducersList = {
[name in TStateSchemaKey]?: Reducer<NonNullable<IStateSchema[name]>>;
};
interface IDynamicModuleLoaderProps {
children: ReactNode;
reducers: TReducersList;
removeAfterUnmount?: boolean;
}
export const DynamicModuleLoader = (props: IDynamicModuleLoaderProps) => {
const { children, reducers, removeAfterUnmount = true } = props;
const dispatch = useDispatch();
const store = useStore() as IReduxStoreWithManager;
useEffect(() => {
const allReducers = store.reducerManager.getReducerMap();
Object.entries(reducers).forEach(([name, reducer]) => {
const mounted = allReducers[name as TStateSchemaKey];
// add
if (!mounted) {
store.reducerManager.add(name as TStateSchemaKey, reducer);
dispatch({ type: `@INIT ${name} reducer` });
}
});
return () => {
if (removeAfterUnmount) {
Object.entries(reducers).forEach(([name]) => {
store.reducerManager.remove(name as TStateSchemaKey);
dispatch({ type: `@DESTROY ${name} reducer` });
});
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// eslint-disable-next-line react/jsx-no-useless-fragment
return <>{children}</>;
};