0

I have been trying to figure out for a long time the best way to handle a redirect for a server-side rendered react app, using react-router v4 and redux.

My App fetches data from an API - sometimes the API responds in a way that makes me need to redirect the user to another URL automatically.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.