added get and create posts with back
This commit is contained in:
@@ -1,19 +1,17 @@
|
||||
import {useCallback, useState} from "react";
|
||||
import {API_URL} from "../config/constants";
|
||||
import PinIcon from "./icons/PinIcon";
|
||||
import CloseIcon from "./icons/CloseIcon";
|
||||
import { EMPTY_FORM, CATEGORIES } from "../config/feedConstants";
|
||||
import { useCreatePost } from "../hooks/useCreatePost";
|
||||
|
||||
export default function PostModal({ onClose, onSuccess }) {
|
||||
const [form, setForm] = useState(EMPTY_FORM);
|
||||
const [errors, setErrors] = useState({});
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [apiError, setApiError] = useState("");
|
||||
const { createAd, loading, error: apiError } = useCreatePost();
|
||||
|
||||
const set = useCallback((k, v) => {
|
||||
setForm(p => ({ ...p, [k]: v }));
|
||||
setErrors(p => ({ ...p, [k]: "" }));
|
||||
setApiError("");
|
||||
}, []);
|
||||
|
||||
const validate = () => {
|
||||
@@ -28,25 +26,20 @@ export default function PostModal({ onClose, onSuccess }) {
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!validate()) return;
|
||||
setLoading(true);
|
||||
setApiError("");
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/api/ads`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new Error(data.message || `Ошибка ${res.status}`);
|
||||
}
|
||||
const newAd = await res.json();
|
||||
|
||||
const payload = {
|
||||
type: form.type, // "loss" | "found"
|
||||
title: form.title.trim(),
|
||||
description: form.description.trim(),
|
||||
category: form.category,
|
||||
date: form.date || null,
|
||||
phone: form.phone.trim(),
|
||||
};
|
||||
|
||||
const newAd = await createAd(payload);
|
||||
if (newAd) {
|
||||
onSuccess(newAd);
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setApiError(err.message || "Не удалось разместить объявление");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -107,15 +100,7 @@ export default function PostModal({ onClose, onSuccess }) {
|
||||
</select>
|
||||
{errors.category && <p className="f-err-msg">{errors.category}</p>}
|
||||
</div>
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">Дата события</label>
|
||||
<input
|
||||
className="f-m-field"
|
||||
type="date"
|
||||
value={form.date}
|
||||
onChange={e => set("date", e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="f-m-group">
|
||||
|
||||
Reference in New Issue
Block a user