| import { useCallback, useEffect } from 'react'; |
| import { useDispatch } from 'react-redux'; |
| import { useLogoutAPIMutation } from '../store/slices/userApiSlice'; |
| import { logout } from '../store/slices/authSlice'; |
| import { apiSlice } from '../store/slices/apiSlice'; |
| import { performLogout } from '../utils/authUtils'; |
|
|
| export const useLogoutHandler = () => { |
| const dispatch = useDispatch(); |
| const [logoutAPI] = useLogoutAPIMutation(); |
|
|
| const handleLogout = useCallback(async () => { |
| await performLogout(dispatch, logoutAPI, logout, apiSlice.util.resetApiState); |
| }, [dispatch, logoutAPI]); |
|
|
| useEffect(() => { |
| const handleGlobalLogout = () => { |
| handleLogout(); |
| }; |
|
|
| window.addEventListener('logout', handleGlobalLogout); |
|
|
| const handleStorageChange = (e) => { |
| if (e.key === 'userToken' && !e.newValue) { |
| handleLogout(); |
| } |
| }; |
|
|
| window.addEventListener('storage', handleStorageChange); |
|
|
| return () => { |
| window.removeEventListener('logout', handleGlobalLogout); |
| window.removeEventListener('storage', handleStorageChange); |
| }; |
| }, [handleLogout]); |
|
|
| return { handleLogout }; |
| }; |
|
|
| export const triggerLogout = () => { |
| window.dispatchEvent(new Event('logout')); |
| }; |