66 lines
1.8 KiB
TypeScript
66 lines
1.8 KiB
TypeScript
import { useCallback } from "react";
|
|
import { useLocation } from "wouter";
|
|
import { useQueryClient } from "@tanstack/react-query";
|
|
import { toast } from "sonner";
|
|
import { trpc } from "@/lib/trpc";
|
|
|
|
export function useAuth() {
|
|
const [, navigate] = useLocation();
|
|
const queryClient = useQueryClient();
|
|
|
|
const meQuery = trpc.auth.me.useQuery(undefined, {
|
|
retry: false,
|
|
staleTime: 60_000,
|
|
});
|
|
|
|
const loginMutation = trpc.auth.login.useMutation({
|
|
onSuccess: async () => {
|
|
await meQuery.refetch();
|
|
await queryClient.invalidateQueries();
|
|
toast.success("Connecté avec succès");
|
|
},
|
|
onError: (e) => toast.error(e.message),
|
|
});
|
|
|
|
const registerMutation = trpc.auth.register.useMutation({
|
|
onSuccess: async () => {
|
|
await meQuery.refetch();
|
|
await queryClient.invalidateQueries();
|
|
toast.success("Compte créé — bienvenue sur QueueMed !");
|
|
},
|
|
onError: (e) => toast.error(e.message),
|
|
});
|
|
|
|
const logoutMutation = trpc.auth.logout.useMutation({
|
|
onSuccess: async () => {
|
|
await queryClient.clear();
|
|
await meQuery.refetch();
|
|
navigate("/");
|
|
toast.success("Déconnecté");
|
|
},
|
|
});
|
|
|
|
const login = useCallback(
|
|
(email: string, password: string) => loginMutation.mutateAsync({ email, password }),
|
|
[loginMutation]
|
|
);
|
|
|
|
const register = useCallback(
|
|
(email: string, password: string, name?: string) =>
|
|
registerMutation.mutateAsync({ email, password, name }),
|
|
[registerMutation]
|
|
);
|
|
|
|
const logout = useCallback(() => logoutMutation.mutate(), [logoutMutation]);
|
|
|
|
return {
|
|
user: meQuery.data ?? null,
|
|
isAuthenticated: !!meQuery.data,
|
|
loading: meQuery.isLoading,
|
|
login,
|
|
register,
|
|
logout,
|
|
isLoggingIn: loginMutation.isPending,
|
|
isRegistering: registerMutation.isPending,
|
|
};
|
|
}
|