global refactoring
This commit is contained in:
45
src/hooks/usePostMutation.js
Normal file
45
src/hooks/usePostMutation.js
Normal file
@@ -0,0 +1,45 @@
|
||||
import { useState } from "react";
|
||||
import { API_URL } from "../config/authConstants";
|
||||
|
||||
/**
|
||||
* Универсальная мутация для создания и обновления объявления.
|
||||
* Заменяет отдельные хуки useCreatePost и useUpdatePost.
|
||||
*
|
||||
* Логика выбора метода:
|
||||
* id передан → PUT /api/v1/posts/:id (обновление)
|
||||
* id не передан → POST /api/v1/posts (создание)
|
||||
*
|
||||
* @returns {{
|
||||
* save: (id: string|null, data: FormData) => Promise<object|null>,
|
||||
* loading: boolean,
|
||||
* error: string,
|
||||
* }}
|
||||
*/
|
||||
export function usePostMutation() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
/**
|
||||
* @param {string|null} id — id объявления при обновлении, null при создании
|
||||
* @param {FormData} data — данные формы
|
||||
* @returns {object|null} — ответ сервера или null при ошибке
|
||||
*/
|
||||
const save = async (id, data) => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const url = id ? `${API_URL}/api/v1/posts/${id}` : `${API_URL}/api/v1/posts`;
|
||||
const method = id ? "PUT" : "POST";
|
||||
const res = await fetch(url, { method, body: data });
|
||||
if (!res.ok) throw new Error(`Ошибка сервера: ${res.status}`);
|
||||
return await res.json();
|
||||
} catch (e) {
|
||||
setError(e.message || "Неизвестная ошибка");
|
||||
return null;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return { save, loading, error };
|
||||
}
|
||||
Reference in New Issue
Block a user