React-redux-starter-kit: Redirect in action

Created on 25 Sep 2016  路  5Comments  路  Source: davezuko/react-redux-starter-kit

I want to redirect after receive response from server in action. What is the best way to do it?

export const redirect = (event) : Function => {
  return (dispatch: Function) => {
    event.preventDefault()
     return axios.post('http://localhost:8080/api/some',data)
            .then((res) => {
                //redirect here
               })
               .catch((err) => {
                    dispatch(handleErrors(err.response.data.error))
               })
   }
}

Most helpful comment

@enesTufekci
In case if you use react-router-redux and routerMiddleware + createBrowserHistory then it should be possible to do that with push from the same module. Then it should be synced with the redux store accordingly. Doesn't this work for you? I'm also curious how would you test routes in this case.

All 5 comments

You can import push or replace function from react-router-redux. They accept url or desctiption object as param, described here

 import { push, replace } from 'react-router-redux'

// and then anywhere in the code
dispatch(push('/url'))
dispatch(replace('/url'))

Thank you I've tried, url is changing but page stills the same, I have tried redux-router but same issue.

I'm using browserHistory.push from react-router.

import { browserHistory } from 'react-router'
...
browserHistory.push('/url')

Only context router is working for me. It is a good practice?
Like,

class Header extends React.Component{
 logout(e){
   e.preventDefault()
   this.props.logout()
   this.context.router.push('/auth')
 }
render(){...}
}
Header.contextTypes = {
  router: React.PropTypes.object.isRequired
}
export default connect(null , {logout})(Header)

@enesTufekci
In case if you use react-router-redux and routerMiddleware + createBrowserHistory then it should be possible to do that with push from the same module. Then it should be synced with the redux store accordingly. Doesn't this work for you? I'm also curious how would you test routes in this case.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dfalling picture dfalling  路  5Comments

nickgnd picture nickgnd  路  4Comments

orielz picture orielz  路  3Comments

marcelloromanelli picture marcelloromanelli  路  5Comments

postalservice14 picture postalservice14  路  4Comments