File size: 1,917 Bytes
4f9f661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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>(() => {
        // Инициализируем состояние сразу из 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 (
        <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;
};