veza/apps/web/src/features/auth/hooks/useAuth.ts

35 lines
853 B
TypeScript
Raw Normal View History

import { useAuthStore } from '../store/authStore';
import { authApi } from '../api/authApi';
import { useQuery } from '@tanstack/react-query';
export const useAuth = () => {
const { user, accessToken, refreshToken, isAuthenticated, logout: storeLogout } = useAuthStore();
const logout = async () => {
if (refreshToken) {
try {
await authApi.logout(refreshToken);
} catch (error) {
console.error('Logout API failed', error);
}
}
storeLogout();
};
// Optional: Query to sync user profile if we have a token but maybe stale user data
// or to verify token validity on app load
useQuery({
queryKey: ['auth', 'me'],
queryFn: authApi.getMe,
enabled: !!accessToken,
retry: false,
});
return {
user,
accessToken,
refreshToken,
isAuthenticated,
logout,
};
};