-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicModuleLoader.tsx
More file actions
46 lines (38 loc) · 1.4 KB
/
DynamicModuleLoader.tsx
File metadata and controls
46 lines (38 loc) · 1.4 KB
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
import { ReactNode, useEffect } from "react";
import { useDispatch, useStore } from "react-redux";
import { Reducer } from "@reduxjs/toolkit";
import { ReduxStoreWithManager, StateSchemaKey } from "@/app/providers/StoreProvider";
export type ReducersList = {
[name in StateSchemaKey]?: Reducer;
};
type ReducersListEntry = [StateSchemaKey, Reducer];
interface DynamicModuleLoaderProps {
reducers: ReducersList;
children: ReactNode;
removeAfterUnmout?: boolean;
}
export const DynamicModuleLoader = ({ children, reducers, removeAfterUnmout }: DynamicModuleLoaderProps) => {
const dispatch = useDispatch();
const store = useStore() as ReduxStoreWithManager;
useEffect(() => {
const mountedReducers = store.reducerManager.getMountedReducers();
Object.entries(reducers).forEach(([name, reducer]) => {
const mounted = mountedReducers[name as StateSchemaKey];
if (!mounted) {
store.reducerManager.add(name as StateSchemaKey, reducer);
dispatch({ type: `@INIT ${name} reducer` });
}
});
return () => {
if (removeAfterUnmout) {
Object.entries(reducers).forEach(([name]) => {
store.reducerManager.remove(name as StateSchemaKey);
dispatch({ type: `@DESTROY ${name} reducer` });
});
}
};
// eslint-disable-next-line
}, []);
// eslint-disable-next-line react/jsx-no-useless-fragment
return <>{children}</>;
};