-
Notifications
You must be signed in to change notification settings - Fork 0
/
DynamicModuleLoader.tsx
48 lines (42 loc) · 1.36 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 {
type StateSchema,
type ReduxStoreWithManager,
type StateSchemaKey,
} from '@/app/providers/StoreProvider';
import { useEffect, type ReactElement } from 'react';
import { type Reducer } from '@reduxjs/toolkit';
import { useDispatch, useStore } from 'react-redux';
export type ReducersList = {
[name in StateSchemaKey]?: Reducer<NonNullable<StateSchema[name]>>;
};
interface DynamicModuleLoaderProps {
children: ReactElement;
reducers: ReducersList;
removeAfterUnmount?: boolean;
}
export const DynamicModuleLoader = (props: DynamicModuleLoaderProps) => {
const { children, reducers, removeAfterUnmount } = props;
const store = useStore() as ReduxStoreWithManager;
const dispatch = useDispatch();
useEffect(() => {
Object.entries(reducers).forEach(([reducerKey, reducer]) => {
const isReducerAdded = store.reducerManager.add(
reducerKey as StateSchemaKey,
reducer,
);
if (isReducerAdded) {
dispatch({ type: `@INIT ${reducerKey} reducer` });
}
});
return () => {
if (removeAfterUnmount) {
Object.keys(reducers).forEach((reducerKey) => {
store.reducerManager.remove(reducerKey as StateSchemaKey);
dispatch({ type: `@DESTROY ${reducerKey} reducer` });
});
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return children;
};