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

169
Visualizações
Change Link To value on condition

I'm trying to implement a login page for my app. When the login button is clicked, a fetch is called and tries to login with the user's info. If the login succeeds, login button's value updates to be the homepage, else it changes back to the login page address. Any idea on how to make it work? I tried <Link to={redirect?"/home":"/"}> but it didn't do anything, and I also tried using a state prop which holds the link value but still had problems with it. Button code:

<Link to={redirect?"/home":"/"}>
    <Button
        onClick={submit}
        variant="primary"
        size="lg"
        className="btn-lg"
        type="submit"
    >
        Login
    </Button>
</Link>

submit (login) code:

const submit = async () => {
    try {
        const res = await fetch("http://localhost:2718/user/login", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(form),
            credentials: 'include',
        });
        if (res.status !== 200) {
            console.log("Error while trying to sign in");
            redirect = false;
        } else {
            console.log("ggoood");
            redirect = true;
        }
    } catch (error) {
        console.log(error);
        redirect = false;
    }
};

*The redirect variable is just a Boolean variable

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

0

Issue

You cannot change the link target after the click. The link was clicked the navigation action is dispatched at the same time the submit callback is called by clicking the button.

Solution

Remove the Link and import the useHistory or useNavigate hook depending on react-router-dom version. When the submit handler is completing imperatively issue the redirect based on auth response.

// for react-router-dom@5
const history = useHistory();
// for react-router-dom@6
const navigate = useNavigate();

...

const submit = async () => {
  try {
    const res = await fetch("http://localhost:2718/user/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(form),
     
      credentials: 'include',
    });
    if (res.status!==200){
      // for react-router-dom@5
      history.replace("/");
      // for react-router-dom@6
      navigate("/", { replace: true });
    } else {
      // for react-router-dom@5
      history.replace("/home");
      // for react-router-dom@6
      navigate("/home", { replace: true });
    }
  } catch (error) {
    // for react-router-dom@5
    history.replace("/");
    // for react-router-dom@6
    navigate("/", { replace: true });
  }
};

...

<Button
  onClick={submit}
  variant="primary"
  size="lg"
  className="btn-lg"
  type="submit"
>
  Login
</Button>
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