-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamicModuleLoader.tsx
44 lines (37 loc) · 1.34 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
import { ReactNode, useEffect } from 'react';
import { useStore } from 'react-redux';
import {
ReduxStoreWithManager,
StateSchemaKey,
} from '@/app/providers/StoreProvider';
import { Reducer } from '@reduxjs/toolkit';
export type ReducerList = {
[name in StateSchemaKey]?: Reducer;
};
// type ReducerListEntry = [StateSchemaKey, Reducer]
interface DynamicModuleLoaderProps {
children: ReactNode;
reducers: ReducerList;
removeAfterUnmount?: boolean;
}
export const DynamicModuleLoader = (props: DynamicModuleLoaderProps) => {
const { children, reducers, removeAfterUnmount = true } = props;
const store = useStore() as ReduxStoreWithManager;
useEffect(() => {
const mountedReducer = store.reducerManager.getMountedReducer();
Object.entries(reducers).forEach(([name, reducer]) => {
const mounted = mountedReducer[name as StateSchemaKey];
if (!mounted) {
store.reducerManager.add(name as StateSchemaKey, reducer);
}
});
return () => {
Object.entries(reducers).forEach(([name]) => {
if (removeAfterUnmount) {
store.reducerManager.remove(name as StateSchemaKey);
}
});
};
}, [reducers, removeAfterUnmount, store.reducerManager]);
return <>{children}</>;
};