57 lines
1.5 KiB
TypeScript
57 lines
1.5 KiB
TypeScript
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
import api from '@/lib/api';
|
|
import type { AuthStatus } from '@/types';
|
|
|
|
export function useAuth() {
|
|
const queryClient = useQueryClient();
|
|
|
|
const authQuery = useQuery({
|
|
queryKey: ['auth'],
|
|
queryFn: async () => {
|
|
const { data } = await api.get<AuthStatus>('/auth/status');
|
|
return data;
|
|
},
|
|
retry: false,
|
|
});
|
|
|
|
const loginMutation = useMutation({
|
|
mutationFn: async (pin: string) => {
|
|
const { data } = await api.post('/auth/login', { pin });
|
|
return data;
|
|
},
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['auth'] });
|
|
},
|
|
});
|
|
|
|
const setupMutation = useMutation({
|
|
mutationFn: async (pin: string) => {
|
|
const { data } = await api.post('/auth/setup', { pin });
|
|
return data;
|
|
},
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['auth'] });
|
|
},
|
|
});
|
|
|
|
const logoutMutation = useMutation({
|
|
mutationFn: async () => {
|
|
const { data } = await api.post('/auth/logout');
|
|
return data;
|
|
},
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['auth'] });
|
|
},
|
|
});
|
|
|
|
return {
|
|
authStatus: authQuery.data,
|
|
isLoading: authQuery.isLoading,
|
|
login: loginMutation.mutateAsync,
|
|
setup: setupMutation.mutateAsync,
|
|
logout: logoutMutation.mutateAsync,
|
|
isLoginPending: loginMutation.isPending,
|
|
isSetupPending: setupMutation.isPending,
|
|
};
|
|
}
|