added files in git
This commit is contained in:
57
src/hooks/useUpdateProfile.js
Normal file
57
src/hooks/useUpdateProfile.js
Normal file
@@ -0,0 +1,57 @@
|
||||
import { useState } from "react";
|
||||
import { API_URL } from "../config/authConstants";
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
const token = localStorage.getItem("token");
|
||||
|
||||
// Используем 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 fetch(`${API_URL}/api/v1/users/${userId}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${token}`,
|
||||
},
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new Error(data.message || `Ошибка ${res.status}`);
|
||||
}
|
||||
|
||||
const updatedUser = await res.json();
|
||||
return updatedUser;
|
||||
} catch (err) {
|
||||
setError(err.message || "Не удалось сохранить профиль");
|
||||
return null;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return { updateProfile, loading, error };
|
||||
}
|
||||
Reference in New Issue
Block a user