devYuraKim / react

udemy - jonas schmedtmann
0 stars 0 forks source link

Re11-worldwise > src > contexts > AuthContext | Multiple Backspace hits needed to return to homepage after logging in via 'START TRACKING NOW' #24

Open devYuraKim opened 1 month ago

devYuraKim commented 1 month ago

Instead of navigating back to /app in the Login component, I centralized navigation in the AuthContext.

Funny thing is, after logging in via the 'START TRACKING NOW' button, I had to hit Backspace three times to return to the Homepage, which didn't happen when I logged out via 'Logout' button in PageNav.

Login component

  function handleSubmit(e) {
    e.preventDefault();
    if (!email || !password) {
      alert("please enter your email and password");
      return;
    }
    login(email, password);
    navigate("/app", { replace: true }); //(1)removed this line of code
  }

AuthContext component

  function login(email, password) {
    if (email === FAKE_USER.email && password === FAKE_USER.password) {
      dispatch({ type: "login", payload: FAKE_USER });
      navigate("/app", { replace: true }); //(2)and moved it here
    } else alert("invalid login credentials");
  }
devYuraKim commented 1 month ago

Scenario 1: replace Only in AppLayout

AppLayout Component:

useEffect(() => {
  if (!isAuthenticated) {
    navigate("/login", { replace: true });
  }
}, [isAuthenticated, navigate]);

login Function:

function login(email, password) {
  if (email === FAKE_USER.email && password === FAKE_USER.password) {
    dispatch({ type: "login", payload: FAKE_USER });
    navigate("/app"); // No replace here
  } else {
    alert("Invalid login credentials");
  }
}

Starting from /app, the user is redirected to /login due to the useEffect in the AppLayout component, which replaces /app in the history stack with /login. This means that when navigating from /login (after login), the history stack only has /login, and hitting the back button will not return the user to /app, but instead to /login and stay there

Scenario 2: replace Only in login Function

AppLayout Component:

useEffect(() => {
  if (!isAuthenticated) {
    navigate("/login");
  }
}, [isAuthenticated, navigate]);

login Function:

function login(email, password) {
  if (email === FAKE_USER.email && password === FAKE_USER.password) {
    dispatch({ type: "login", payload: FAKE_USER });
    navigate("/app", { replace: true }); // Replace here
  } else {
    alert("Invalid login credentials");
  }
}

The stack should be [ /, /app, /app ] after login. Why is there an extra /app added to the stack?

devYuraKim commented 1 month ago

Still can't figure out why an extra /app is added to the stack. However, setting {replace:true} in useEffect resolve the issue.

  useEffect(
    function () {
      if (!isAuthenticated) {
        navigate("/login", { replace: true });
      }
    },
    [isAuthenticated, navigate]
  );