50 lines
1.7 KiB
JavaScript
50 lines
1.7 KiB
JavaScript
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 };
|
||
}
|