If the API responds in a way that causes me to need to redirect, I store the path that the user should be directed to in the redux store. (My API returns an error object with a "redirect" variable I can lookup in my routes file to insert into the store as the redirect path).
Importantly, this is just storing the path in the redux store.
case (typeof error["redirect"] !== "undefined" && error["redirect"] !== null): {
dispatch({
type: RENDER_REDIRECT,
payload: routes[error["redirect"]]
});
break;
}
I have a component called "RenderRedirect", this component is always rendered in the main app, but takes special action if this.props shows the redirect as "null" and nextProps redirect as !null.
This means a redirect has been triggered.
It uses history.push to change the URL, and then clears the redirect out of the store using another action.
This works particularly well because I don't have to worry about server-side rendering erring, because this situation can only happen client-side.
Anytime I need to trigger a redirect I can easily dispatch the above action with a path as a payload.
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from "react-router-dom";
import { clearRedirect } from '../../../actions';
class RenderRedirect extends Component {
componentWillReceiveProps(nextProps) {
// Detect redirect, perform redirect, clear redirect
const { redirect, history, clearRedirectAction } = this.props;
// Detect redirect
if(redirect === null && nextProps.redirect !== null) {
history.push(nextProps.redirect);
clearRedirectAction();
}
}
render() {
const { redirect } = this.props;
if (redirect !== null) {
return (
<div>
<p className={"profile-instructions"}>Redirecting...</p>
</div>
)
} else {
return null;
}
}
}
const mapStateToProps = (state) => ({
redirect: state.redirect
})
const mapDispatchToProps = (dispatch) => ({
clearRedirectAction: () => dispatch(clearRedirect())
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(RenderRedirect));