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; logout: () => void; isLoading: boolean; error: Error | null; } const AuthContext = createContext(undefined); export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => { const [isAuthenticated, setIsAuthenticated] = useState(() => { // Инициализируем состояние сразу из localStorage 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 ( {children} ); }; export const useAuth = () => { const context = useContext(AuthContext); if (!context) { throw new Error('useAuth must be used within an AuthProvider'); } return context; };