func optimization

This commit is contained in:
Den Piligrim
2026-01-31 18:44:09 +03:00
parent 6db895bcc7
commit 27310c0bc0
39 changed files with 1989 additions and 539 deletions
+32 -12
View File
@@ -3,34 +3,54 @@ import api from '../api';
interface AuthContextType {
token: string | null;
isAuthenticated: boolean;
login: (token: string) => void;
logout: () => void;
isAuthenticated: boolean;
}
const AuthContext = createContext<AuthContextType>(null!);
const AuthContext = createContext<AuthContextType | null>(null);
export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
const [token, setToken] = useState<string | null>(localStorage.getItem('token'));
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [token, setToken] = useState<string | null>(() => {
const savedToken = localStorage.getItem('token');
if (savedToken) {
api.defaults.headers.common['Authorization'] = `Bearer ${savedToken}`;
}
return savedToken;
});
const login = (newToken: string) => {
localStorage.setItem('token', newToken);
api.defaults.headers.common['Authorization'] = `Bearer ${newToken}`;
setToken(newToken);
};
const logout = () => {
localStorage.removeItem('token');
delete api.defaults.headers.common['Authorization'];
setToken(null);
};
useEffect(() => {
if (token) {
localStorage.setItem('token', token);
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
} else {
localStorage.removeItem('token');
delete api.defaults.headers.common['Authorization'];
}
}, [token]);
const login = (newToken: string) => setToken(newToken);
const logout = () => setToken(null);
return (
<AuthContext.Provider value={{ token, login, logout, isAuthenticated: !!token }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);
};