Redirect on Login and Logout
To complete the login flow we are going to need to do two more things.
- Redirect the user to the homepage after they login.
- And redirect them back to the login page after they logout.
We are going to use the useHistory
hook that comes with React Router. This will allow us to use the browser’s History API.
Redirect to Home on Login
First, initialize useHistory
hook in the beginning of src/containers/Login.js
.
const history = useHistory();
Make sure to add it below the export default function Login() {
line.
Then update the handleSubmit
method in src/containers/Login.js
to look like this:
async function handleSubmit(event) {
event.preventDefault();
try {
await Auth.signIn(email, password);
userHasAuthenticated(true);
history.push("/");
} catch (e) {
alert(e.message);
}
}
Also, import useHistory
from React Router in the header of src/containers/Login.js
.
import { useHistory } 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.
Redirect to Login After Logout
Now we’ll do something very similar for the logout process.
Add the useHistory
hook in the beginning of App
component.
const history = useHistory();
Import useHistory
from React Router in the header of src/App.js
.
import { useHistory } from "react-router-dom";
Add the following to the bottom of the handleLogout
function in our src/App.js
.
history.push("/login");
So our handleLogout
function should now look like this.
async function handleLogout() {
await Auth.signOut();
userHasAuthenticated(false);
history.push("/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.
For help and discussion
Comments on this chapter