File size: 1,237 Bytes
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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'));
};