Reputation: 1117
I'm trying to get the previous location from react router. I've set up a reducer to listen for @@router/LOCATION_CHANGE and store the current and new locations but this action doesn't seem to get fired anymore?
Reducer looks like this:
const initialState = {
previousLocation: null,
currentLocation: null,
};
const routerLocations = function (state = initialState, action) {
const newstate = { ...state };
switch (action.type) {
case "@@router/LOCATION_CHANGE":
newState.previousLocation = state.currentLocation;
newState.currentLocation = action.payload;
return newState
default:
return state;
}
}
export default routerLocations;
Is @@router/LOCATION_CHANGE the right thing to listen for?
I'm using
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-router-redux": "^4.0.8",
Upvotes: 2
Views: 7353
Reputation: 2599
It's better to import action type from react-router-redux
directly like this:
import { LOCATION_CHANGE } from 'react-router-redux'
and then use it in your reducer. This action return new object after history
is changed. Probably, you need only pathname
property.
So, your reducer should be like this:
import { LOCATION_CHANGE } from 'react-router-redux'
const initialState = {
previousLocation: null,
currentLocation: null,
}
export default (state = initialState, action) => {
switch (action.type) {
case LOCATION_CHANGE:
return {
previousLocation: state.currentLocation,
currentLocation: action.payload.pathname,
}
default:
return state
}
}
I faced with the problem that this action doens't fire on initial render. I've investigated and realized that it can be used only with history
earlier than version v4.0.0-2.
This related to the internal implementation of the react-router-redux
. Under the hood of the library, during initial render getCurrentLocation
of history
object is being called, which was removed in history version v4.0.0-2.
That's why you should downgrade your history
version or try to subscribe on history
changes and dispatch the action by yourself on initial render.
Upvotes: 4