I'm making React application, and I have small problem when logging user out. "Sign out" button is Link element which leads to Logout component. Then Logout component calls logout function with access token which is sent to the backend, user and access token are cleared from my store, and page redirects user to Login page. This all works (User is logged out successfully), but I have some slight problem with user experience. In fact, my Logout component first tries to redirect to Login page before logout function is executed, and my router checks if there is a user (there still is), and redirects him to homepage. After that user is logged out and redirected to login page.
How can I handle this?
Here is Sign out button
<Link to='/logout' className='menu-link px-5'>
Sign Out
</Link>
import React, { useEffect } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { Redirect, Switch } from 'react-router-dom';
import * as auth from './redux/AuthRedux';
import { logout } from './redux/AuthCRUD';
import { RootState } from '../../../setup';
export function Logout() {
const accessToken: string = useSelector<RootState>(({ auth }) => auth.accessToken, shallowEqual) as string;
const dispatch = useDispatch();
useEffect(() => {
logout(accessToken).then((response) => {
dispatch(auth.actions.logout());
});
}, [dispatch]);
return (
<Switch>
<Redirect to='/auth/login' />
</Switch>
);
}
accessToken gets removed from the store when you dispatch the logout action, so that allows you to use it's presence as an indication you still have a user. If you have an access token, show a spinner (for example), the user isn't logged out. If you don't have an access token, then you're logged out and can redirect.
export function Logout() {
const accessToken: string = useSelector<RootState>(({ auth }) => auth.accessToken, shallowEqual) as string;
const dispatch = useDispatch();
useEffect(() => {
logout(accessToken).then((response) => {
dispatch(auth.actions.logout());
});
}, [dispatch]);
return accessToken ? <Spinner /> : <Redirect to='/auth/login' />
}
While I'm here, you don't need shallowEqual as the second argument to your useSelector because it's just a string.