To complete the login flow we are going to need to do two more things.

  1. Redirect the user to the homepage after they login.
  2. And redirect them back to the login page after they logout.

We are going to use the useNavigate hook that comes with React Router. This will allow us to use the browser’s History API.

Redirect to Home on Login

Change indicator First, initialize useNavigate hook in the beginning of src/containers/Login.tsx.

const nav = useNavigate();

Make sure to add it below the export default function Login() { line.

Change indicator Then update the handleSubmit method in src/containers/Login.tsx to look like this:

async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
  event.preventDefault();

  try {
    await Auth.signIn(email, password);
    userHasAuthenticated(true);
    nav("/");
  } catch (error) {
    if (error instanceof Error) {
      alert(error.message);
    } else {
      alert(String(error));
    }
  }
}

Change indicator Also, import useNavigate from React Router in the header of src/containers/Login.tsx.

import { useNavigate } from "react-router-dom";

Now if you head over to your browser and try logging in, you should be redirected to the homepage after you’ve been logged in.

React Router v6 redirect home after login screenshot

Redirect to Login After Logout

Now we’ll do something very similar for the logout process.

Change indicator Add the useNavigate hook in the beginning of App component in src/App.tsx.

const nav = useNavigate();

Change indicator Import useNavigate from React Router in the header of src/App.tsx.

import { useNavigate } from "react-router-dom";

Change indicator Add the following to the bottom of the handleLogout function in our src/App.tsx.

nav("/login");

So our handleLogout function should now look like this.

async function handleLogout() {
  await Auth.signOut();

  userHasAuthenticated(false);

  nav("/login");
}

This redirects us back to the login page once the user logs out.

Now if you switch over to your browser and try logging out, you should be redirected to the login page.

You might have noticed while testing this flow that since the login call has a bit of a delay, we might need to give some feedback to the user that the login call is in progress. Also, we are not doing a whole lot with the errors that the Auth package might throw. Let’s look at those next.