mirror of
https://github.com/Sea-Haven-Industries/shoc-frontend-new.git
synced 2026-09-30 04:33:11 +00:00
60 lines
1.9 KiB
TypeScript
60 lines
1.9 KiB
TypeScript
import {
|
|
useMutation,
|
|
useQuery,
|
|
useQueryClient,
|
|
type UseMutationResult,
|
|
type UseQueryResult,
|
|
} from "@tanstack/react-query";
|
|
import { useNavigate } from "react-router";
|
|
import { toast } from "react-toastify";
|
|
import * as authApi from "@/domain/auth/api/auth-api";
|
|
import type { AuthUser, LoginCredentials } from "@/domain/auth/types/auth-user";
|
|
import { queryKeys } from "@/infra/query-key/query-key";
|
|
import { startQueryBroadcast, stopQueryBroadcast } from "@/lib/query/setup-query-broadcast";
|
|
|
|
export function useSession(): UseQueryResult<AuthUser | null, Error> {
|
|
return useQuery({
|
|
queryKey: queryKeys.auth.session(),
|
|
queryFn: authApi.getSession,
|
|
retry: false,
|
|
staleTime: 5 * 60 * 1000,
|
|
});
|
|
}
|
|
|
|
export function useLogin(): UseMutationResult<AuthUser, Error, LoginCredentials> {
|
|
const navigate = useNavigate();
|
|
const queryClient = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: (credentials: LoginCredentials) => authApi.login(credentials),
|
|
meta: { suppressErrorToast: true },
|
|
onSuccess: (user) => {
|
|
stopQueryBroadcast(queryClient);
|
|
queryClient.setQueryData(queryKeys.auth.session(), user);
|
|
startQueryBroadcast(queryClient, user.id);
|
|
toast.success("Login successful!");
|
|
navigate("/");
|
|
},
|
|
});
|
|
}
|
|
|
|
export function useLogout(): UseMutationResult<void, Error, void> {
|
|
const navigate = useNavigate();
|
|
const queryClient = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: authApi.logout,
|
|
onSuccess: () => {
|
|
stopQueryBroadcast(queryClient);
|
|
queryClient.setQueryData(queryKeys.auth.session(), null);
|
|
toast.info("You have been logged out");
|
|
navigate("/login");
|
|
},
|
|
onError: (error: Error) => {
|
|
stopQueryBroadcast(queryClient);
|
|
queryClient.setQueryData(queryKeys.auth.session(), null);
|
|
toast.error(error.message || "Logout failed");
|
|
navigate("/login");
|
|
},
|
|
});
|
|
}
|