Files
nahodka-front/src/hooks/useProfile.js
2026-09-10 00:57:31 +03:00

50 lines
1.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useCallback } from "react";
import { useTranslation } from 'react-i18next';
import { API_URL } from "../config/authConstants";
import { apiFetch } from "../api/apiClient";
/**
* useProfile — хук для получения свежих данных профиля с бэка.
* Делает GET /api/v1/users/{id} и возвращает актуальные данные пользователя
* (включая аватар), которые могут устареть в локальном контексте, если
* профиль менялся с другого устройства.
*
* fetchProfile возвращает { success, data, error }.
*/
export function useProfile() {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const fetchProfile = useCallback(async (userId) => {
if (!userId) {
const message = t('profile.fetchMissingUserId');
setError(message);
return { success: false, data: null, error: message };
}
setLoading(true);
setError("");
try {
const res = await apiFetch(`${API_URL}/api/v1/users/${userId}`);
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.message || t('profile.fetchErrorWithStatus', { status: res.status }));
}
const user = await res.json();
return { success: true, data: user, error: null };
} catch (err) {
const message = err.message || t('profile.fetchError');
setError(message);
return { success: false, data: null, error: message };
} finally {
setLoading(false);
}
}, [t]);
return { fetchProfile, loading, error };
}