I have a very simple project you can find on:
https://codesandbox.io/s/issue-looping-between-last-2-routes-xhxu1
On file: /src/store/middlewares.ts
I have the following middlewares:
import { Dispatch, Middleware, AnyAction } from "redux";
import { RootState } from "./rootReducer";
import { createStandardAction } from "typesafe-actions";
export const sendMessage = createStandardAction("message/SEND")<string>();
export const locationMiddleware: Middleware<
{},
RootState,
Dispatch<AnyAction>
> = store => next => action => {
if (action.type === "@@router/LOCATION_CHANGE") {
store.dispatch(sendMessage("BEFORE D-DAY")); // <--- THIS LINE IS CAUSING THE ISSUE
const result = next(action);
store.dispatch(sendMessage("AFTER D-DAY"));
return result;
} else {
return next(action);
}
};
export const messageMiddleware: Middleware<
{},
RootState,
Dispatch<AnyAction>
> = store => next => action => {
if (action.type === "message/SEND") {
console.log("Message: ", action.payload);
}
return next(action);
};
As you can see, on every @@router/LOCATION_CHANGE
I dispatch two actions with a message which I capture on another middleware: messageMiddleware
and I do a console.log
with them. These actions are dispatched before and after the call to: next(action)
.
The issue I'm facing is with line: store.dispatch(sendMessage("BEFORE D-DAY"));
.
When that line is enabled you can do the following steps to reproduce the issue:
- open the app on the root location (aka:
Page 01
) - click link:
Page 02
- click link:
Page 03
- click back button (you will be redirected to:
Page 02
) - click back button (you will be redirected to:
Page 03
, instead ofPage 01
#FAIL#
)
Please, notice that the back button is the one below (not the acutal button of the browser):
In the other hand, if I uncomment the line which I referenced as the issue, then when clicking the back button the behavior is as expected: -> Page 02 -> Page 01
straight forward.
It seems that this middleware system doesn't like to dispatch an action before the call to: next(action)
.
Any idea on how to solve this situation in a good way and keep logging the actions before and after the calls to next(action)
?
Requirement: Use middlewares.
Thanks!