Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current location from react-router-redux

How do you get the current location when using "react-router-redux"?

This is the routing state:

{
    routing: {
        locationBeforeTransition: {
            pathname: "/foo",
            search: "",
            hash: "",
            state: null,
            action: "PUSH",
            key: "e8jfk"
        },
        query: null,
        $searchBase: {
            search: "",
            searchBase: ""
        }
    }
}

I can clearly access the current location as state.routing.locationBeforeTransition.pathname, but the name "locationBeforeTransition" seems like it would be the previous page location, not the current one. It also seems odd that this is the only property in my routing state. I suspect I am doing something wrong.

Here is a simplified reducer that only has routing:

reducer.js

import { combineReducers, createStore, applyMiddleware, compose } from 'redux';
import { routerReducer, routerMiddleware } from 'react-router-redux';
import { browserHistory } from 'react-router';
import thunkMiddleware from 'redux-thunk';

const reducer = combineReducers({ 
  routing: routerReducer, 
});

export const store = createStore(reducer, {}, compose(
    applyMiddleware(
      routerMiddleware(browserHistory), 
      thunkMiddleware
    ),
    window.devToolsExtension ? window.devToolsExtension() : f => f
  )
);
like image 601
Don P Avatar asked Aug 19 '16 15:08

Don P


1 Answers

You can't actually get that from the redux store, because According to the react-router-redux docs in How do I access router state in a container component?:

You should not read the location state directly from the Redux store. This is because React Router operates asynchronously (to handle things such as dynamically-loaded components) and your component tree may not yet be updated in sync with your Redux state. You should rely on the props passed by React Router, as they are only updated after it has processed all asynchronous code.

like image 98
Ori Drori Avatar answered Nov 09 '22 16:11

Ori Drori