All files / src/features/auth/hooks use-auth.ts

74.19% Statements 46/62
100% Branches 0/0
75% Functions 18/24
74.19% Lines 46/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158                            3x   7x 1x 1x           3x 8x 8x 8x   8x 4x   4x 4x       2x     2x     2x 2x           2x     2x 2x 2x 2x   2x               3x 8x 8x 8x   8x 4x   4x 4x       2x     2x     2x 2x           2x     2x 2x 2x 2x   2x               3x 8x 8x 8x 8x   8x                                                                                      
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { startTransition } from 'react';
import type {
  SigninData,
  SignupData,
  AuthResponse,
} from '../services/auth.service';
import { authService } from '../services/auth.service';
import { useAuthStore } from '@/store/auth-store';
import { useToast } from '@/hooks/use-toast';
import { useAuthSync } from '@/hooks/use-store-sync';
import { AUTH_SUCCESS_MESSAGES, TOAST_DURATION } from '@/constants/auth';
 
// Query keys for React Query
export const authKeys = {
  all: ['auth'] as const,
  user: () => [...authKeys.all, 'user'] as const,
  profile: () => [...authKeys.all, 'profile'] as const,
  status: () => [...authKeys.all, 'status'] as const,
};
 
/**
 * Hook for sign in with improved error handling and state management
 */
export const useSignin = () => {
  const queryClient = useQueryClient();
  const { setLoadingState, setError, login } = useAuthStore();
  const { successToast, errorToast } = useToast();
 
  return useMutation({
    mutationFn: (data: SigninData) => authService.signin(data),
    onMutate: () => {
      setLoadingState('signin', true);
      setError(null);
    },
    onSuccess: (response: AuthResponse) => {
      // Save auth data to Zustand store (which persists to localStorage)
      login(response.user, response.jwt);
 
      // Invalidate and refetch user data
      queryClient.invalidateQueries({ queryKey: authKeys.user() });
 
      // Show success message
      startTransition(() => {
        successToast(
          AUTH_SUCCESS_MESSAGES.SIGNIN(response.user.username),
          TOAST_DURATION.DEFAULT
        );
      });
 
      setLoadingState('signin', false);
    },
    onError: (error: Error) => {
      console.error('Sign in error:', error);
      setError(error.message);
      startTransition(() => {
        errorToast(error.message, TOAST_DURATION.DEFAULT);
      });
      setLoadingState('signin', false);
    },
  });
};
 
/**
 * Hook for sign up with improved error handling and state management
 */
export const useSignup = () => {
  const queryClient = useQueryClient();
  const { setLoadingState, setError, login } = useAuthStore();
  const { successToast, errorToast } = useToast();
 
  return useMutation({
    mutationFn: (data: SignupData) => authService.signup(data),
    onMutate: () => {
      setLoadingState('signup', true);
      setError(null);
    },
    onSuccess: (response: AuthResponse) => {
      // Save auth data to Zustand store
      login(response.user, response.jwt);
 
      // Invalidate and refetch user data
      queryClient.invalidateQueries({ queryKey: authKeys.user() });
 
      // Show success message
      startTransition(() => {
        successToast(
          AUTH_SUCCESS_MESSAGES.SIGNUP(response.user.username),
          TOAST_DURATION.DEFAULT
        );
      });
 
      setLoadingState('signup', false);
    },
    onError: (error: Error) => {
      console.error('Sign up error:', error);
      setError(error.message);
      startTransition(() => {
        errorToast(error.message, TOAST_DURATION.DEFAULT);
      });
      setLoadingState('signup', false);
    },
  });
};
 
/**
 * Hook for logout with proper state cleanup
 */
export const useLogout = () => {
  const queryClient = useQueryClient();
  const { setLoadingState } = useAuthStore();
  const { successToast, warningToast } = useToast();
  const { syncLogout } = useAuthSync();
 
  return useMutation({
    mutationFn: async () => {
      setLoadingState('logout', true);
 
      try {
        // Call API logout (if endpoint exists)
        await authService.logout();
      } catch (error) {
        console.error('API logout failed:', error);
        // Don't throw error for API failures - continue with local cleanup
      }
    },
    onSuccess: () => {
      // Clear all authentication and user data from stores
      syncLogout();
 
      // Clear React Query cache for auth-related data
      queryClient.invalidateQueries({ queryKey: authKeys.all });
      queryClient.removeQueries({ queryKey: authKeys.all });
 
      // Show success message
      startTransition(() => {
        successToast(AUTH_SUCCESS_MESSAGES.LOGOUT, TOAST_DURATION.DEFAULT);
      });
 
      console.log('🔐 [Auth] Logout completed successfully');
    },
    onError: (error: Error) => {
      console.error('Logout error:', error);
 
      // Even if there's an error, we should still clear local state
      syncLogout();
      queryClient.removeQueries({ queryKey: authKeys.all });
 
      startTransition(() => {
        warningToast('Logged out (with some issues)', TOAST_DURATION.DEFAULT);
      });
    },
    onSettled: () => {
      setLoadingState('logout', false);
    },
  });
};