react-redux-starter-kit
react-redux-starter-kit copied to clipboard
Redirect in action
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))
})
}
}
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.