Why are listeners notified before middleware is finished?
See original GitHub issueI have a bug in my application that I am trying to work out how to fix and the issue goes as follows:
- An action is triggered
- I have middleware which records state before and after the action is fired (either side of
next(action)
) - I have some React components with a
useLayoutEffect()
hook that sometimes dispatch actions - Some actions seem to trigger immediate renders when calling
next()
in middleware, which triggers an immediate dispatch and the middleware is not getting the state after the result of the action but its getting the state after the result of the 2nd action, that is the dispatch fromuseLayoutEffect
is occurring in the middle ofnext(action)
and not after the middleware has run.
I am trying to reproduce this in a simplified test case and having a hard time in doing so, what I have determined is that for some actions my application renders immediately when listener()
is invoked inside dispatch and for other actions the re-render occurs after the listener and I haven’t yet worked out how to reproduce the first case where the re-render is immediate despite trying here: https://codesandbox.io/s/immutable-architecture-2535n?file=/src/App.tsx
I can’t seem to see any difference in the next(action)
call of either action:
Regardless my question is why are listeners notified at all until after middleware is finished? Otherwise isn’t there always the risk that a listener dispatches another action and the middleware is unable to act on the finished state of the first action?
Issue Analytics
- State:
- Created 2 years ago
- Comments:10 (6 by maintainers)
Top GitHub Comments
Sure. If you can manage to come up with any additional unit tests that capture the exact flow of the current behavior, we’d be interested in those even if we don’t end up accepting any changes to the core logic, so we at least have something that would visibly indicate that hypothetical future logic changes are actually changing that flow.
Also note that the current
master
branch is an as-yet-unreleased TS conversion of the library. You may want to pick up with the4.x
branch, which is still plain JS. Code can get ported either way, of course.@markerikson thanks as long as its open to discussion that works for me. I appreciate the fine line you have to tread to keep everyone happy and was why I made this issue to determine whether it was intentional or not and can go from there.
Also appreciate regardless of the original intent it could be seen as a breaking change because someone may be depending on the inverse (I can’t think of the use case but I’m sure they wouldn’t think of mine off the cuff either).
I will take a stab at both approaches and report back.