Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
Redirecting when using React + Redux

I'm used react-router-dom + redux + middleware Redux Thunk. I got index page, when loading it calls the method of requesting data to the server. This method is implemented as an asynchronous function that is passed to dispatch (and which is actually intercepted to execute the Redux Thunk).

During the execution of the asynchronous data request function, if errors occur, a redirect to 404/500 pages is performed. The implementation of this part of the function is as follows: as you know, each component for which routing is implemented receives props with the corresponding fields (match, location, history), then the same props are passed to the asynchronous action as an argument, and thus the possibilities are already available in it redirects via history.push / go / etc.

The problem is that there is a binding to the fact that the component must have this type of props data in principle. This, of course, can be solved by passing props to the desired component or using withRouter for it. I also found an old solution with importing history from the package of the same name directly into the file with the desired action, but with this method, although the path in the address bar changes, but the transition itself is not.

Actually, I want to understand, maybe I'm generally trying to shove a redirect where it shouldn't be, and hence all the problems? Where is it better to implement such things as redirect if you are making requests to the server within asynchronous actions / middlware? I would be grateful for indicating the direction of the search, articles on the topic, best practices, etc.

// MainPage.js

class MainPage extends PureComponent {
    componentDidMount() {
        this.props.fetchData(this.props);
    }

    render() {
        const SpinnerModal = withModal(Spinner, { bg: false, interactionsDisabled: true });
        if (!this.props.index) return <SpinnerModal/>;

        return (
            <>
                <Promo index={this.props.index}/>
            </>
        );
    }
}
const mapStateToProps = (state) => ({ index: serverSelectors.serverIndexSelector(state) });
const mapDispatchToProps = (dispatch) => bindActionCreators(serverActions, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(MainPage);

 
// redux/server/actions.js

export const fetchData = (props) => async (dispatch, getState, api) => {
    try {
        const response = await api.get(props.uri);
        dispatch({
            type: types.SERVER_FETCH_PAGE_DATA,
            payload: { data: response.data },
        });
    } catch (error) {
        switch (error.status) {
            case 404: {
                props.history.push("/404");
                break;
            }
            case 500: {
                props.history.push("/500");
                break;
            }
            default:
        }
    }
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are correct, the underlying assumption is that your component must have this data in principal. However, with the development of functional components, more and more hooks have emerged to ease such inconveniences. In you case the useHistory hook can be incredibly useful.

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

This hook rids you of passing history from one component to another.

A simple (yet amateurish) solution would be to simply change location. For Example:

window.location.href = "/404"

In any event, if you're not taking advantage of any special capabilities that come with using a Pure Component, a stateless (functional) component would perform much better. Especially in this scenario.

Edit0:

I researched your question a bit more and I found this article that describes an interesting concept. Using redux middleware to facilitate redirections. The writer of the article describes a situation where upon user registration, we need to make an api call and also redirect the user to another page.

The author achieves this by chaining 2 middleware. The first to make the api call and the second to update a redirectTo property in the global state.

If the API call is successful, a redirect action is dispatched to update the redirectTo property in the global state with the redirect path. Finally, using a simple if statement in the registration form component that is connected to the redirectTo property in the global state:

if (props.redirectTo) {
  return <Redirect to={props.redirectTo} />;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!