Files
nahodka-front/src/hooks/useUpdateProfile.js
2026-09-03 00:29:19 +03:00

72 lines
3.0 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";
/**
* 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 || "");
// Новый аватар: compressImage может вернуть Blob (а не File), поэтому
// проверяем по Blob — File является его подклассом, так что оба случая покрыты.
// Blob может не иметь .name, а Spring ждёт filename в multipart-части — задаём явно.
if (profileData.avatar instanceof Blob) {
formData.append("avatar", profileData.avatar, profileData.avatar.name || "avatar.jpg");
}
// Явное удаление аватара без замены новым файлом
if (profileData.removeAvatar) {
formData.append("removeAvatar", "true");
}
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 };
}