Files
nahodka-front/src/hooks/useCreatePost.js
2026-07-09 00:09:45 +03:00

42 lines
1.2 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";
export function useCreatePost() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [success, setSuccess] = useState(false);
const createAd = async (formData) => { // ← принимаем FormData
setLoading(true);
setError(null);
try {
const token = localStorage.getItem("token");
const res = await fetch(`${API_URL}/api/v1/posts`, {
method: "POST",
headers: {
// Content-Type НЕ указываем — браузер сам добавит multipart/form-data с boundary
"Authorization": `Bearer ${token}`,
},
body: formData, // ← передаём FormData
});
const data = await res.json(); // ← объявляем ПОСЛЕ await res
if (!res.ok) {
throw new Error(data.message || "Error creating ad");
}
setSuccess(true);
return data;
} catch (e) {
setError(e.message);
return null;
} finally {
setLoading(false);
}
};
return { createAd, loading, error, success };
}