1- import { useCallback } from 'react' ;
1+ import { useCallback , useEffect } from 'react' ;
2+ import { useNavigate } from 'react-router-dom' ;
23import { useAppStore } from '../store' ;
34
5+ type CurrentUser = {
6+ id ?: string ;
7+ email ?: string ;
8+ phone ?: string ;
9+ avatar ?: string ;
10+ name ?: string ;
11+ } ;
12+
13+ /**
14+ * Hook to get currently logged user
15+ * @returns {object | undefined } user data as object or undefined if user is not logged in
16+ */
17+ export function useCurrentUser ( ) : CurrentUser | undefined {
18+ const [ state ] = useAppStore ( ) ;
19+ return state . currentUser ;
20+ }
21+
422/**
523 * Hook to detect is current user authenticated or not
624 * @returns {boolean } true if user is authenticated, false otherwise
@@ -20,12 +38,31 @@ export function useIsAuthenticated() {
2038 * @returns {function } calling this event logs out current user
2139 */
2240export function useEventLogout ( ) {
41+ const navigate = useNavigate ( ) ;
2342 const [ , dispatch ] = useAppStore ( ) ;
2443
2544 return useCallback ( ( ) => {
2645 // TODO: AUTH: add auth and tokens cleanup here
2746 // sessionStorageDelete('access_token');
2847
2948 dispatch ( { type : 'LOG_OUT' } ) ;
30- } , [ dispatch ] ) ;
49+ navigate ( '/' , { replace : true } ) ; // Redirect to home page by reloading the App
50+ } , [ dispatch , navigate ] ) ;
51+ }
52+
53+ /**
54+ * Adds watchdog and calls different callbacks on user login and logout
55+ * @param {function } afterLogin callback to call after user login
56+ * @param {function } afterLogout callback to call after user logout
57+ */
58+ export function useAuthWatchdog ( afterLogin : ( ) => void , afterLogout : ( ) => void ) {
59+ const [ state , dispatch ] = useAppStore ( ) ;
60+
61+ useEffect ( ( ) => {
62+ if ( state . isAuthenticated ) {
63+ afterLogin ?.( ) ;
64+ } else {
65+ afterLogout ?.( ) ;
66+ }
67+ } , [ state . isAuthenticated , dispatch , afterLogin , afterLogout ] ) ;
3168}
0 commit comments