Files
nahodka-front/src/hooks/useSearchPosts.js
SlimusMinus 7f59ee1f38 fixed code
2026-08-11 00:24:07 +03:00

44 lines
1.3 KiB
JavaScript

import { useState, useCallback } from "react";
import { API_URL } from "../config/authConstants";
/**
* useSearchPosts — поиск объявлений по городу.
* Ходит на GET /api/v1/posts/search?city=..., возвращает список без пагинации.
*
* @returns {Object} { posts, loading, error, searchPosts }
*/
export function useSearchPosts() {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const searchPosts = useCallback(async (city) => {
setLoading(true);
setError("");
try {
const params = new URLSearchParams();
if (city) params.set("city", city);
const res = await fetch(`${API_URL}/api/v1/posts/search?${params}`);
if (!res.ok) throw new Error(`Error ${res.status}`);
const data = await res.json();
const list = Array.isArray(data) ? data : [];
const normalized = list.map(ad => ({
...ad,
type: ad.type ? ad.type.toLowerCase() : "loss"
}));
setPosts(normalized);
return normalized;
} catch (err) {
setError(err.message || "Failed to search posts");
setPosts([]);
return [];
} finally {
setLoading(false);
}
}, []);
return { posts, loading, error, searchPosts };
}