Step 7. Handle logout requests
Of course, you can’t have a protected app without providing the ability to log out. Luckily, this is a fairly easy task.
Open up the views/logout.js
file and import the following:
-
FRUser
from the Ping SDK -
useEffect
anduseContext
from React -
useNavigate
from React Router -
AppContext
from the global state module.
reactjs-todo/client/views/logout.js
+ import { FRUser } from '@forgerock/javascript-sdk';
- import React from 'react';
+ import React, { useContext, useEffect } from 'react';
+ import { useNavigate } from 'react-router-dom';
+ import { AppContext } from '../global-state';
@@ collapsed @@
Since logging out requires a network request, we need to wrap it in a useEffect
and pass in a callback function with the following functionality:
reactjs-todo/client/views/logout.js
@@ collapsed @@
export default function Logout() {
+ const [_, { setAuthentication, setEmail, setUser }] = useContext(AppContext);
+ const navigate = useNavigate();
+ useEffect(() => {
+ async function logout() {
+ try {
+ await FRUser.logout();
+ setAuthentication(false);
+ setEmail('');
+ setUser('');
+ navigate('/');
+ } catch (err) {
+ console.error(`Error: logout; ${err}`);
+ }
+ }
+ logout();
+ }, []);
return <Loading classes="pt-5" message="You're being logged out ..." />;
}
Since we only want to call this method once, after the component mounts, we will pass in an empty array as a second argument for useEffect()
. After FRUser.logout()
completes, we just empty or falsify the global state to clean up and redirect back to the home page.
You have now completed the coding part of this tutorial, and can proceed to the final step, Test the app.