-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamicModuleLoader.tsx
48 lines (37 loc) · 1.46 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
import { Reducer } from '@reduxjs/toolkit';
import { ReactNode, useEffect } from 'react';
import { useStore } from 'react-redux';
import { useAppDispatch } from '../../hooks/useAppDispatch';
import { ReduxWithReducerManager, StateSchema, StateSchemaKey } from '@/app/providers/StoreProvider';
export type ReducersList = {
[name in StateSchemaKey]?: Reducer<NonNullable<StateSchema[name]>>;
};
interface DynamicModuleLoaderProps {
reducers: ReducersList;
removeAfterUnmount?: boolean;
children: ReactNode;
}
export const DynamicModuleLoader: React.FC<DynamicModuleLoaderProps> = (props) => {
const { reducers, children, removeAfterUnmount = true } = props;
const dispatch = useAppDispatch();
const store = useStore() as ReduxWithReducerManager;
useEffect(() => {
const mountedReducers = store.reducerManager.getReducerMap();
Object.entries(reducers).forEach(([name, reducer]) => {
const mounted = Boolean(mountedReducers[name as StateSchemaKey]);
if (!mounted) {
store.reducerManager.add(name as StateSchemaKey, reducer);
dispatch({ type: `@@INIT ${name} reducer` });
}
});
return () => {
if (removeAfterUnmount) {
Object.entries(reducers).forEach(([name]) => {
store.reducerManager.remove(name as StateSchemaKey);
dispatch({ type: `@@DESTROY ${name} reducer` });
});
}
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps
return <>{children}</>;
};