1 import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
2 import { apiRequest } from "@/lib/queryClient";
3 import { useToast } from "@/hooks/use-toast";
4 import type { User, InsertUser } from "@shared/schema";
5
6 export function useAuth() {
7 const { toast } = useToast();
8 const queryClient = useQueryClient();
9
10 const {
11 data: user,
12 isLoading,
13 error,
14 } = useQuery<User | null>({
15 queryKey: ["/api/user"],
16 queryFn: () => fetch("/api/user").then(res => res.ok ? res.json() : null),
17 });
18
19 const loginMutation = useMutation({
20 mutationFn: async (credentials: any) => {
21 const res = await apiRequest("POST", "/api/login", credentials);
22 return res.json();
23 },
24 onSuccess: (user: User) => {
25 queryClient.setQueryData(["/api/user"], user);
26 toast({ title: "Welcome back!", description: `Signed in as ${user.firstName}` });
27 },
28 onError: (error: Error) => {
29 toast({
30 title: "Login failed",
31 description: error.message,
32 variant: "destructive",
33 });
34 },
35 });
36
37 const registerMutation = useMutation({
38 mutationFn: async (userData: InsertUser) => {
39 const res = await apiRequest("POST", "/api/register", userData);
40 return res.json();
41 },
42 onSuccess: (user: User) => {
43 queryClient.setQueryData(["/api/user"], user);
44 toast({ title: "Account created", description: "You are now logged in." });
45 },
46 onError: (error: Error) => {
47 toast({
48 title: "Registration failed",
49 description: error.message,
50 variant: "destructive",
51 });
52 },
53 });
54
55 const logoutMutation = useMutation({
56 mutationFn: async () => {
57 await apiRequest("POST", "/api/logout");
58 },
59 onSuccess: () => {
60 queryClient.setQueryData(["/api/user"], null);
61 toast({ title: "Signed out", description: "See you next time!" });
62 },
63 });
64
65 return {
66 user,
67 isLoading,
68 isAuthenticated: !!user,
69 loginMutation,
70 registerMutation,
71 logoutMutation,
72 };
73 }