-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcontext.ts
39 lines (31 loc) · 1017 Bytes
/
context.ts
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
import {
createContext,
createElement,
useContext,
useMemo,
} from 'react';
import { Store } from 'redux';
import {
PatchedStore,
patchStore,
useSelector as useSelectorOrig,
useTrackedState as useTrackedStateOrig,
} from 'reactive-react-redux';
import { State, Action } from './store/actions';
// Context based APIs
const Context = createContext(new Proxy({}, {
get() { throw new Error('use Provider'); },
}) as PatchedStore<State, Action>);
export const Provider: React.FC<{ store: Store<State, Action> }> = ({
store,
children,
}) => {
const value = useMemo(() => patchStore(store), [store]);
return createElement(Context.Provider, { value }, children);
};
export const useDispatch = () => useContext(Context).dispatch;
export const useSelector = <Selected>(
selector: (state: State) => Selected,
) => useSelectorOrig(useContext(Context), selector);
export const useTrackedState = () => useTrackedStateOrig(useContext(Context));
export const useStore = () => useContext(Context);