Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda