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

143
Visualizações
Redirect using navigate() to the same URL updating the state in react

'/'URL Login handler function

const loginHandler = (e) => {
        e.preventDefault();
        Services.login(email, password)
          .then((Res) => {
            if(Res.data==="success"){
              navigate('/home')
            }
            else {
              navigate('/',{
                state: {
                  msg: Res.data,
                }})
            }
          })
          .catch((error) => {
            console.log(error);
          });
      };

On Res.data other than success I want to redirect to the same /Url by updating the state of a component so that I can display proper error message on the same page and prevent user to navigate to /home Url . How can I do that?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think you'll find it's not too useful to navigate to the same page as you intend. Seems more straightforward to keep some state on the current page and show/hide an error message based on that state

import React, { useState } from 'react';

const ThisPage = () => {
    const [failed, setFailed] = useState(false);
    
    const loginHandler = () => {
        ....when you get to your error
        }else{
            setFailed(true);
        }
    }
    //then render an error message on this page if failed
    return(
        <div>
            <SomeOtherContent />
            <div hidden={!failed}>Something went wrong!</div>
        </div>
    );
}

If you really need to navigate to the same page, you could look into using useContext() to keep a state that is outside of the page component so that it would still be there when you redirect to the same component (and rerender it). https://reactjs.org/docs/hooks-reference.html#usecontext

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