fixed code v2
This commit is contained in:
@@ -1,16 +1,27 @@
|
||||
import {useState} from "react";
|
||||
import {API_URL} from "../config/authConstants";
|
||||
import {apiFetch} from "../api/apiClient";
|
||||
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 = async (userId, profileData) => {
|
||||
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("");
|
||||
|
||||
@@ -36,17 +47,19 @@ export function useUpdateProfile() {
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new Error(data.message || `Ошибка ${res.status}`);
|
||||
throw new Error(data.message || t('profile.updateErrorWithStatus', { status: res.status }));
|
||||
}
|
||||
|
||||
return await res.json();
|
||||
const updatedUser = await res.json();
|
||||
return { success: true, data: updatedUser, error: null };
|
||||
} catch (err) {
|
||||
setError(err.message || "Failed to save profile");
|
||||
return null;
|
||||
const message = err.message || t('profile.updateError');
|
||||
setError(message);
|
||||
return { success: false, data: null, error: message };
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
}, [t]);
|
||||
|
||||
return { updateProfile, loading, error };
|
||||
}
|
||||
Reference in New Issue
Block a user