Files
nahodka-front/src/hooks/useRegister.js
2026-08-03 02:44:57 +03:00

69 lines
1.8 KiB
JavaScript

import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { API_URL } from "../config/authConstants";
import { saveTokens } from "../api/apiClient";
export function useCheckLogin(login) {
const [checking, setChecking] = useState(false);
const [exists, setExists] = useState(false);
useEffect(() => {
if (!login || login.length < 3) {
setExists(false);
return;
}
const timer = setTimeout(async () => {
try {
setChecking(true);
const res = await fetch(`${API_URL}/api/v1/auth/check-login?login=${encodeURIComponent(login)}`);
const json = await res.json();
setExists(json.exists);
} catch (e) {
console.error(e);
} finally {
setChecking(false);
}
}, 400);
return () => clearTimeout(timer);
}, [login]);
return { checking, exists };
}
export function useRegister() {
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [success, setSuccess] = useState(false);
const register = async ({ name, login, password }) => {
setLoading(true);
setError(null);
try {
const res = await fetch(`${API_URL}/api/v1/auth/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, login, password }),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.message || "Ошибка регистрации");
}
saveTokens(data.token, data.refreshToken);
setSuccess(true);
setTimeout(() => navigate("/feed"), 1500);
} catch (e) {
setError(e.message);
} finally {
setLoading(false);
}
};
return { register, loading, error, success };
}