Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 703
Vikramaditya Avatar asked Jun 28 '16 18:06

Vikramaditya


People also ask

How do I navigate in Redux?

To handle your app's navigation state in Redux, you can pass your own navigation prop to a navigator. Once you pass your own navigation prop to the navigator, the default navigation prop gets destroyed. You must construct your own navigation prop with state , dispatch , and addListener properties.

How do I get data from Redux in react JS?

It's simple to get access to the store inside a React component – no need to pass the store as a prop or import it, just use the connect function from React Redux, and supply a mapStateToProps function that pulls out the data you need. Then, inside the component, you can pass that data to a function that needs it.

What is action reducer and dispatch?

Reducer -> Describes how your action transfers state into the next state. It checks which action took place and based on the action it updates the store. Dispatch -> Way how we execute the action. eg: Dispatch the action to the reducer. Then reducer will check what to do and the store gets updated.


1 Answers

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
like image 152
Kokovin Vladislav Avatar answered Nov 02 '22 05:11

Kokovin Vladislav