react-redux-starter-kit icon indicating copy to clipboard operation
react-redux-starter-kit copied to clipboard

Redirect in action

Open nstfkc opened this issue 8 years ago • 5 comments

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

nstfkc avatar Sep 25 '16 19:09 nstfkc

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

m4recek avatar Sep 25 '16 20:09 m4recek

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

nstfkc avatar Sep 29 '16 16:09 nstfkc

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

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

jgallow avatar Sep 30 '16 12:09 jgallow

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)

nstfkc avatar Sep 30 '16 12:09 nstfkc

@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.

proton1k avatar Oct 12 '16 11:10 proton1k