-
Notifications
You must be signed in to change notification settings - Fork 0
/
DynamicModuleLoader.tsx
54 lines (46 loc) · 1.56 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
53
54
import { ReactNode, useEffect } from 'react';
import { useDispatch, useStore } from 'react-redux';
import { Reducer } from '@reduxjs/toolkit';
import {
ReduxStoreWithManager,
StateSchema,
StateSchemaKey,
} from '@/app/providers/StoreProvider';
export type ReducersList = {
[name in StateSchemaKey]?: Reducer<NonNullable<StateSchema[name]>>;
};
type ReducersListEntry = [StateSchemaKey, Reducer];
interface DynamicModuleLoaderProps {
reducers: ReducersList;
removeAfterUnmount?: boolean;
children: ReactNode;
}
export const DynamicModuleLoader = (props: DynamicModuleLoaderProps) => {
const { children, reducers, removeAfterUnmount = true } = props;
const dispatch = useDispatch();
const store = useStore() as ReduxStoreWithManager;
useEffect(() => {
const mountedReducers = store.reducerManager.getMountedReducers();
// console.log(reducers);
Object.entries(reducers).forEach(([name, reducer]) => {
const mounted = mountedReducers[name as StateSchemaKey];
if (!mounted) {
store.reducerManager.add(name as StateSchemaKey, reducer);
console.log(store.reducerManager.getMountedReducers());
dispatch({ type: `@init ${name} reducer` });
}
});
return () => {
if (removeAfterUnmount) {
Object.entries(reducers).forEach(([name, reducer]) => {
store.reducerManager.remove(name as StateSchemaKey);
dispatch({ type: `@destroy ${name} reducer` });
});
}
};
}, []);
return (
// eslint-disable-next-line react/jsx-no-useless-fragment
<>{children}</>
);
};