Skip to content
This repository was archived by the owner on Dec 29, 2022. It is now read-only.

Commit f67b5cf

Browse files
committed
support multiple rex store instances in a project
1 parent 3b8a794 commit f67b5cf

1 file changed

Lines changed: 25 additions & 27 deletions

File tree

src/index.tsx

Lines changed: 25 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4,36 +4,34 @@ import React, {
44
createContext,
55
useContext,
66
Dispatch,
7-
SetStateAction
7+
SetStateAction,
8+
Context
89
} from "react";
910

10-
const createStore = (store: object) => {
11-
const intializedStore = {};
12-
for (const item in store) {
13-
intializedStore[item] = new store[item]();
14-
}
15-
return intializedStore;
16-
};
17-
18-
export interface RexProviderProps {
19-
children: ReactNode;
20-
store: object;
21-
}
22-
23-
const initalAppState = {};
24-
25-
const AppContext = createContext(initalAppState);
26-
27-
const { Provider } = AppContext;
28-
29-
export const useRex = () => {
30-
const store = useContext(AppContext);
31-
return store;
32-
};
11+
export const createRexStore: <T extends { [key: string]: Rex<any> }>(
12+
store: T
13+
) => {
14+
RexProvider: ({ children }: { children: React.ReactNode }) => JSX.Element;
15+
useRex: () => T;
16+
} = store => {
17+
let RexContext: Context<typeof store>;
18+
19+
const useRex = () => {
20+
const store = useContext(RexContext);
21+
return store;
22+
};
23+
24+
const RexProvider = ({ children }: { children: ReactNode }) => {
25+
const intializedStore: typeof store = {};
26+
for (const item in store) {
27+
intializedStore[item] = new store[item]();
28+
}
29+
RexContext = createContext(intializedStore);
30+
const { Provider } = RexContext;
31+
return <Provider value={intializedStore}>{children}</Provider>;
32+
};
3333

34-
export const RexProvider = ({ children, store }: RexProviderProps) => {
35-
const initializedStore = createStore(store);
36-
return <Provider value={initializedStore}>{children}</Provider>;
34+
return { RexProvider, useRex };
3735
};
3836

3937
class Rex<S> {

0 commit comments

Comments
 (0)