fixed search and add hints
This commit is contained in:
@@ -1,41 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { useSearchPosts } from "./useSearchPosts";
|
||||
|
||||
/**
|
||||
* Поиск объявлений по нескольким выбранным городам, с объединением
|
||||
* результатов без дублей. Автоматически перезапускается при смене
|
||||
* selectedCities.
|
||||
*/
|
||||
export function useCityFeed(selectedCities) {
|
||||
const { loading: cityLoading, searchPosts } = useSearchPosts();
|
||||
const [cityAds, setCityAds] = useState([]);
|
||||
|
||||
const searchCities = useCallback((citiesToSearch) => {
|
||||
if (!citiesToSearch.length) return Promise.resolve([]);
|
||||
return Promise.all(citiesToSearch.map(c => searchPosts(c))).then(results => {
|
||||
const seen = new Set();
|
||||
const merged = [];
|
||||
results.flat().forEach(ad => {
|
||||
if (!seen.has(ad.id)) {
|
||||
seen.add(ad.id);
|
||||
merged.push(ad);
|
||||
}
|
||||
});
|
||||
return merged;
|
||||
});
|
||||
}, [searchPosts]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedCities.length === 0) {
|
||||
setCityAds([]);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
searchCities(selectedCities).then(result => {
|
||||
if (!cancelled) setCityAds(result);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [selectedCities, searchCities]);
|
||||
|
||||
return { cityAds, cityLoading, searchCities };
|
||||
}
|
||||
@@ -16,8 +16,22 @@ function extractPage(data) {
|
||||
return { items, last };
|
||||
}
|
||||
|
||||
/**
|
||||
* Собирает query-параметры фильтров ленты для GET /api/v1/posts.
|
||||
* @param {{ type?: string|null, categories?: string[], cities?: string[] }} filters
|
||||
*/
|
||||
function appendFilters(params, filters) {
|
||||
if (!filters) return;
|
||||
if (filters.type) params.set("type", filters.type);
|
||||
(filters.categories || []).forEach(c => params.append("category", c));
|
||||
(filters.cities || []).forEach(c => params.append("city", c));
|
||||
}
|
||||
|
||||
/**
|
||||
* Управляет основной лентой объявлений: загрузка, пагинация, поиск.
|
||||
* Поиск и фильтры (тип, категории, города) выполняет сервер — так бесконечная
|
||||
* прокрутка подгружает именно подходящие объявления, а не фильтрует страницы
|
||||
* «общей» ленты на клиенте.
|
||||
*/
|
||||
export function useFeedPosts() {
|
||||
const [ads, setAds] = useState([]);
|
||||
@@ -36,9 +50,13 @@ export function useFeedPosts() {
|
||||
// «устаревшим», и в ленте остаются только объявления со 2-й страницы.
|
||||
const firstPageLoadedRef = useRef(false);
|
||||
const resetInFlightRef = useRef(false);
|
||||
// Фильтры последней загрузки первой страницы: следующие страницы бесконечной
|
||||
// прокрутки обязаны запрашиваться с теми же фильтрами.
|
||||
const filtersRef = useRef(null);
|
||||
|
||||
const loadFeed = useCallback(async (pageNum = 0, search = "", append = false) => {
|
||||
const loadFeed = useCallback(async (pageNum = 0, search = "", append = false, filters) => {
|
||||
if (append && (!firstPageLoadedRef.current || resetInFlightRef.current)) return;
|
||||
if (!append) filtersRef.current = filters || null;
|
||||
if (!append) resetInFlightRef.current = true;
|
||||
const requestId = ++requestIdRef.current;
|
||||
if (pageNum === 0) {
|
||||
@@ -50,6 +68,7 @@ export function useFeedPosts() {
|
||||
try {
|
||||
const params = new URLSearchParams({ page: pageNum, size: PAGE_SIZE });
|
||||
if (search) params.set("search", search);
|
||||
appendFilters(params, append ? filtersRef.current : filters);
|
||||
|
||||
const res = await fetch(`${API_URL}/api/v1/posts?${params}`);
|
||||
if (!res.ok) throw new Error(`Error ${res.status}`);
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
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 };
|
||||
}
|
||||
Reference in New Issue
Block a user