Files
nahodka-front/src/hooks/useUpdateProfile.js
2026-08-03 02:44:57 +03:00

52 lines
1.8 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} from "react";
import {API_URL} from "../config/authConstants";
import {apiFetch} from "../api/apiClient";
/**
* useUpdateProfile — хук для обновления профиля пользователя.
* Отправляет PUT /api/v1/users/{id} с FormData (поддерживает загрузку аватара).
*/
export function useUpdateProfile() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const updateProfile = async (userId, profileData) => {
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 || `Ошибка ${res.status}`);
}
return await res.json();
} catch (err) {
setError(err.message || "Failed to save profile");
return null;
} finally {
setLoading(false);
}
};
return { updateProfile, loading, error };
}