Files
nahodka-front/src/hooks/useUpdateProfile.js
SlimusMinus db37befb8d Support new backend contracts: single-flight refresh, ad impression tokens, error handling
- apiFetch: proactive refresh, cross-tab single-flight via Web Locks, no logout on transient errors
- AuthContext: save tokens returned on own login change, revoke refresh on logout, sync tabs
- Ads: X-Session-Id, impressionToken in impression/click, IAB viewability, safe http(s) targetUrl
- STOMP: refresh before CONNECT, stop reconnect loop on dead session, /user/queue/errors behind flag
- Auth form: password 8 chars / 72 bytes; 429/413 messages via describeApiError
- My posts with auth + moderation badges; post form step validation and field limits
- Map: escape user text in Yandex hint/template

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 02:03:42 +03:00

75 lines
3.3 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";
import { describeApiError, readApiError } from "../api/apiErrors";
/**
* 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 apiError = await readApiError(res);
throw new Error(describeApiError(apiError, t('profile.updateErrorWithStatus', { status: res.status })));
}
// При смене своего логина в ответе есть новые token/refreshToken —
// их сохраняет AuthContext.updateUser (старые больше не действуют).
const updatedUser = await res.json();
return { success: true, data: updatedUser, error: null };
} catch (err) {
const message = describeApiError(err, t('profile.updateError'));
setError(message);
return { success: false, data: null, error: message };
} finally {
setLoading(false);
}
}, [t]);
return { updateProfile, loading, error };
}