65 lines
2.5 KiB
JavaScript
65 lines
2.5 KiB
JavaScript
import { useState, useCallback } from "react";
|
||
import { useTranslation } from 'react-i18next';
|
||
import { API_URL } from "../config/authConstants";
|
||
import { apiFetch } from "../api/apiClient";
|
||
|
||
/**
|
||
* useUpdateProfile — хук для обновления профиля пользователя.
|
||
* Отправляет PUT /api/v1/users/{id} с FormData (поддерживает загрузку аватара).
|
||
*
|
||
* updateProfile возвращает { success, data, error } — data содержит
|
||
* обновлённого пользователя при успехе, error — текст ошибки при неудаче.
|
||
*/
|
||
export function useUpdateProfile() {
|
||
const { t } = useTranslation();
|
||
const [loading, setLoading] = useState(false);
|
||
const [error, setError] = useState("");
|
||
|
||
const updateProfile = useCallback(async (userId, profileData) => {
|
||
if (!userId) {
|
||
const message = t('profile.updateMissingUserId');
|
||
setError(message);
|
||
return { success: false, data: null, error: message };
|
||
}
|
||
|
||
setLoading(true);
|
||
setError("");
|
||
|
||
try {
|
||
// Используем FormData — чтобы отправить файл аватара вместе с текстовыми полями
|
||
const formData = new FormData();
|
||
formData.append("id", userId);
|
||
formData.append("firstName", profileData.firstName || "");
|
||
formData.append("lastName", profileData.lastName || "");
|
||
formData.append("login", profileData.login || "");
|
||
formData.append("phone", profileData.phone || "");
|
||
formData.append("email", profileData.email || "");
|
||
|
||
// Если avatar — это File (новый файл), отправляем как часть FormData
|
||
if (profileData.avatar instanceof File) {
|
||
formData.append("avatar", profileData.avatar);
|
||
}
|
||
|
||
const res = await apiFetch(`${API_URL}/api/v1/users/${userId}`, {
|
||
method: "PUT",
|
||
body: formData,
|
||
});
|
||
|
||
if (!res.ok) {
|
||
const data = await res.json().catch(() => ({}));
|
||
throw new Error(data.message || t('profile.updateErrorWithStatus', { status: res.status }));
|
||
}
|
||
|
||
const updatedUser = await res.json();
|
||
return { success: true, data: updatedUser, error: null };
|
||
} catch (err) {
|
||
const message = err.message || t('profile.updateError');
|
||
setError(message);
|
||
return { success: false, data: null, error: message };
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
}, [t]);
|
||
|
||
return { updateProfile, loading, error };
|
||
} |