use-auth.ts61 lines, 1.6 KB
| 1 | 'use client'; |
| 2 | |
| 3 | import { useMutation, useQueryClient } from '@tanstack/react-query'; |
| 4 | import { useRouter } from 'next/navigation'; |
| 5 | import { toast } from 'sonner'; |
| 6 | import { loginUser, registerUser } from '../api/auth'; |
| 7 | import { useAuthStore } from '@/stores/auth-store'; |
| 8 | import type { LoginCredentials, RegisterData } from '@/types'; |
| 9 | |
| 10 | export function useLogin() { |
| 11 | const router = useRouter(); |
| 12 | const queryClient = useQueryClient(); |
| 13 | const { setAuth } = useAuthStore(); |
| 14 | |
| 15 | return useMutation({ |
| 16 | mutationFn: (credentials: LoginCredentials) => loginUser(credentials), |
| 17 | onSuccess: (data) => { |
| 18 | setAuth(data.user, data.accessToken); |
| 19 | queryClient.invalidateQueries({ queryKey: ['user'] }); |
| 20 | toast.success('Logged in successfully'); |
| 21 | router.push('/'); |
| 22 | }, |
| 23 | onError: (error: Error) => { |
| 24 | toast.error(`Login failed`, { |
| 25 | description: error.message || 'Please try again later.', |
| 26 | }); |
| 27 | }, |
| 28 | }); |
| 29 | } |
| 30 | |
| 31 | export function useRegister() { |
| 32 | const router = useRouter(); |
| 33 | |
| 34 | return useMutation({ |
| 35 | mutationFn: (data: RegisterData) => registerUser(data), |
| 36 | onSuccess: () => { |
| 37 | toast.success('Registered successfully'); |
| 38 | router.push('/login'); |
| 39 | }, |
| 40 | onError: (error: Error) => { |
| 41 | toast.error(`Registration failed`, { |
| 42 | description: error.message || 'Please try again later.', |
| 43 | }); |
| 44 | }, |
| 45 | }); |
| 46 | } |
| 47 | |
| 48 | export function useLogout() { |
| 49 | const router = useRouter(); |
| 50 | const { clearAuth } = useAuthStore(); |
| 51 | const queryClient = useQueryClient(); |
| 52 | |
| 53 | const logout = () => { |
| 54 | clearAuth(); |
| 55 | queryClient.clear(); |
| 56 | toast.success('Logged out successfully'); |
| 57 | router.push('/login'); |
| 58 | }; |
| 59 | |
| 60 | return { logout }; |
| 61 | } |