Home > Software design >  Change Link To value on condition
Change Link To value on condition

Time:02-15

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

CodePudding user response:

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>
  • Related