Skip to content

Commit

Permalink
[fix] Send most updated state to manager middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
ntucker committed May 28, 2019
1 parent 3a7def4 commit e0b8212
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
9 changes: 5 additions & 4 deletions src/react-integration/provider/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useReducer, useMemo } from 'react';
import { useReducer, useMemo, useRef } from 'react';
import compose from 'lodash/fp/compose';
import { Middleware } from '../../types';

Expand All @@ -12,6 +12,8 @@ export default function createEnhancedReducerHook(
startingState: React.ReducerState<R>,
): [React.ReducerState<R>, React.Dispatch<React.ReducerAction<R>>] => {
const [state, realDispatch] = useReducer(reducer, startingState);
const store = useRef({ state });
store.current.state = state;

let outerDispatch = useMemo(() => {
let dispatch: React.Dispatch<React.ReducerAction<R>> = () => {
Expand All @@ -22,14 +24,13 @@ export default function createEnhancedReducerHook(
};
// closure here around dispatch allows us to change it after middleware is constructed
const middlewareAPI = {
// state is not needed in useMemo() param list since it's retrieved as function
getState: () => state,
getState: () => store.current.state,
dispatch: (action: React.ReducerAction<R>) => dispatch(action),
};
const chain = middlewares.map(middleware => middleware(middlewareAPI));
dispatch = compose(chain)(realDispatch);
return dispatch;
}, [realDispatch]);
}, [realDispatch, store]);
return [state, outerDispatch];
};
return useEnhancedReducer;
Expand Down
7 changes: 5 additions & 2 deletions src/state/NetworkManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,12 +151,15 @@ export default class NetworkManager {
case 'rest-hooks/purge':
case 'rest-hooks/rpc':
case 'rest-hooks/receive':
// only receive after new state is computed
next(action);
if (action.meta.url in this.fetched) {
this.handleReceive(action);
}
// fallthrough is on purpose
return;
default:
return next(action);
next(action);
return;
}
};
};
Expand Down

0 comments on commit e0b8212

Please sign in to comment.