Get current location from react-router-redux

10,028

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.

Share:
10,028
Don P
Author by

Don P

@ Facebook currently

Updated on June 28, 2022

Comments

  • Don P
    Don P almost 2 years

    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
      )
    );