import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import type { User } from "@shared/models/auth";
async function fetchUser(): Promise<User | null> {
const response = await fetch("/api/auth/user", {
credentials: "include",
});
if (response.status === 401) {
return null;
}
if (!response.ok) {
throw new Error(`${response.status}: ${response.statusText}`);
}
return response.json();
}
export function useAuth() {
const queryClient = useQueryClient();
const { data: user, isLoading } = useQuery<User | null>({
queryKey: ["/api/auth/user"],
queryFn: fetchUser,
retry: false,
staleTime: 1000 * 60 * 5,
});
const logoutMutation = useMutation({
mutationFn: async () => {
const res = await fetch("/api/auth/logout", {
method: "POST",
credentials: "include",
});
if (!res.ok) {
window.location.href = "/api/logout";
}
},
onSuccess: () => {
queryClient.setQueryData(["/api/auth/user"], null);
window.location.href = "/";
},
onError: () => {
window.location.href = "/api/logout";
},
});
return {
user,
isLoading,
isAuthenticated: !!user,
logout: logoutMutation.mutate,
isLoggingOut: logoutMutation.isPending,
};
}