How to access current location in reducer (redux-router)?

10,582

1.way - pass pathname with particular action through redux-thunk and getState()

const someAction = data =>(dispatch,getState)=>{
   dispatch({
      type:'SOME_ACTION',
      pathname:getState().router.pathname
   })
}

2.way - write middleware and pass pathname with every action

///write middleware
export const attachPathNameToAction = store => next => action=>{
    action.pathname = store.getState().router.pathname //<-----passing pathname
    next(action)
};


///then in reducer you allways can get pathname
case 'SOME_ACTION':
    let pathname = action.pathname \\  <-------------
    return {...state, action.data}

3.way - pass pathname from component's this.props.location.pathname

//in component 
let {pathname}= this.props.location;
this.props.someAction(data, pathname);

//workflow:  component -> action -> reducer
Share:
10,582
Vikramaditya
Author by

Vikramaditya

Updated on July 17, 2022

Comments

  • Vikramaditya
    Vikramaditya almost 2 years

    How would i get the current path and query of the current location with redux-router in reducer. I am able to get the pathname easily inside the component with mapStateToProps, but i want to access the current path in reducer. I am using redux-router 1.0.0-beta7, react-router 1.0.3.

  • Tomer
    Tomer over 7 years
    The middleware solution is great! Thanks for that. I really wonder why they don't have a plugin for it.
  • Erwin Wessels
    Erwin Wessels over 6 years
    Note that it's ... .router.location.pathname, not ... .router.pathname.