Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda