| import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'; |
| import { useMutation } from '@tanstack/react-query'; |
| import { login } from '@/api/auth/authApi'; |
| import { LoginRequest } from '@/api/auth/types'; |
|
|
| interface AuthContextType { |
| isAuthenticated: boolean; |
| login: (data: LoginRequest) => Promise<void>; |
| logout: () => void; |
| isLoading: boolean; |
| error: Error | null; |
| } |
|
|
| const AuthContext = createContext<AuthContextType | undefined>(undefined); |
|
|
| export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => { |
| const [isAuthenticated, setIsAuthenticated] = useState<boolean>(() => { |
| |
| return !!localStorage.getItem('authToken'); |
| }); |
|
|
| const loginMutation = useMutation({ |
| mutationFn: (data: LoginRequest) => login(data), |
| onSuccess: (data) => { |
| localStorage.setItem('authToken', data.access_token); |
| setIsAuthenticated(true); |
| }, |
| onError: (error) => { |
| console.error('Login Error:', error); |
| }, |
| }); |
|
|
| const loginHandler = async (data: LoginRequest) => { |
| await loginMutation.mutateAsync(data); |
| }; |
|
|
| const logout = () => { |
| localStorage.removeItem('authToken'); |
| setIsAuthenticated(false); |
| }; |
|
|
| return ( |
| <AuthContext.Provider |
| value={{ |
| isAuthenticated, |
| login: loginHandler, |
| logout, |
| isLoading: loginMutation.isPending, |
| error: loginMutation.error, |
| }} |
| > |
| {children} |
| </AuthContext.Provider> |
| ); |
| }; |
|
|
| export const useAuth = () => { |
| const context = useContext(AuthContext); |
| if (!context) { |
| throw new Error('useAuth must be used within an AuthProvider'); |
| } |
| return context; |
| }; |