dvdzkwsk / react-redux-starter-kit

Get started with React, Redux, and React-Router.
MIT License
10.29k stars 2.2k forks source link

Redirect in action #1021

Open nstfkc opened 8 years ago

nstfkc commented 8 years ago

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))
               })
   }
}
m4recek commented 8 years ago

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'))
nstfkc commented 8 years ago

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

jgallow commented 8 years ago

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

import { browserHistory } from 'react-router'
...
browserHistory.push('/url')
nstfkc commented 8 years ago

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)
proton1k commented 7 years ago

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