summaryrefslogtreecommitdiff
path: root/src/components/StateProvider.js
diff options
context:
space:
mode:
authorHaishan <[email protected]>2020-01-04 16:56:53 +0800
committerHaishan <[email protected]>2020-01-04 16:56:53 +0800
commit85d948def8e1a75c5e5cce2d5518e9702b6e0452 (patch)
tree796865645a1137338a310a0b8f1625d890d3c939 /src/components/StateProvider.js
parenta06a32131759cd3b34000cfd5a098df875fddae7 (diff)
feat: support change latency test url #286
Diffstat (limited to 'src/components/StateProvider.js')
-rw-r--r--src/components/StateProvider.js38
1 files changed, 34 insertions, 4 deletions
diff --git a/src/components/StateProvider.js b/src/components/StateProvider.js
index 1f3e4d9..23041fe 100644
--- a/src/components/StateProvider.js
+++ b/src/components/StateProvider.js
@@ -4,6 +4,7 @@ import produce, * as immer from 'immer';
const {
createContext,
memo,
+ useMemo,
useRef,
useEffect,
useCallback,
@@ -11,10 +12,11 @@ const {
useState
} = React;
+export { immer };
+
const StateContext = createContext(null);
const DispatchContext = createContext(null);
-
-export { immer };
+const ActionsContext = createContext(null);
export function useStoreState() {
return useContext(StateContext);
@@ -24,7 +26,12 @@ export function useStoreDispatch() {
return useContext(DispatchContext);
}
-export default function Provider({ initialState, children }) {
+export function useStoreActions() {
+ return useContext(ActionsContext);
+}
+
+// boundActionCreators
+export default function Provider({ initialState, actions = {}, children }) {
const stateRef = useRef(initialState);
const [state, setState] = useState(initialState);
const getState = useCallback(() => stateRef.current, []);
@@ -49,11 +56,17 @@ export default function Provider({ initialState, children }) {
},
[getState]
);
+ const boundActions = useMemo(() => bindActions(actions, dispatch), [
+ actions,
+ dispatch
+ ]);
return (
<StateContext.Provider value={state}>
<DispatchContext.Provider value={dispatch}>
- {children}
+ <ActionsContext.Provider value={boundActions}>
+ {children}
+ </ActionsContext.Provider>
</DispatchContext.Provider>
</StateContext.Provider>
);
@@ -76,3 +89,20 @@ export function connect(mapStateToProps) {
return Connected;
};
}
+
+// steal from https://github.com/reduxjs/redux/blob/master/src/bindActionCreators.ts
+function bindAction(action, dispatch) {
+ return function() {
+ return dispatch(action.apply(this, arguments));
+ };
+}
+function bindActions(actions, dispatch) {
+ const boundActions = {};
+ for (const key in actions) {
+ const action = actions[key];
+ if (typeof action === 'function') {
+ boundActions[key] = bindAction(action, dispatch);
+ }
+ }
+ return boundActions;
+}