43 lines
1.2 KiB
JavaScript
43 lines
1.2 KiB
JavaScript
import { useState } from "react";
|
|
import { useNavigate } from "react-router-dom";
|
|
import { API_URL } from "../config/authConstants";
|
|
import { useAuthContext } from "../context/AuthContext";
|
|
|
|
export function useAuth() {
|
|
const navigate = useNavigate();
|
|
const { login: saveAuth } = useAuthContext();
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState("");
|
|
|
|
const login = async (login, password) => {
|
|
if (!login || !password) { setError("Enter login and password"); return; }
|
|
setLoading(true); setError("");
|
|
|
|
try {
|
|
const res = await fetch(`${API_URL}/api/v1/auth`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ login, password }),
|
|
});
|
|
|
|
if (!res.ok) {
|
|
const data = await res.json().catch(() => ({}));
|
|
throw new Error(data.message || "Invalid login or password");
|
|
}
|
|
|
|
const { token, user } = await res.json();
|
|
|
|
// Сохраняем в глобальный контекст + localStorage
|
|
saveAuth(user, token);
|
|
|
|
navigate("/feed");
|
|
} catch (err) {
|
|
setError(err.message);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
return { login, loading, error };
|
|
}
|