Improve search functionality by adding a debounce to input
Adds a debounce mechanism to the search input field on the search page, delaying search execution for 500ms after the user stops typing to prevent excessive API calls and improve performance. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 517dfa7b-26ac-463d-a6e1-a58c6df97188 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Event-Id: 4dc54121-0b3f-4812-85d1-73cc6650fb75 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/f209e72a-0939-48fa-84fc-57854de71967/517dfa7b-26ac-463d-a6e1-a58c6df97188/jdAEdU5 Replit-Helium-Checkpoint-Created: true
This commit is contained in:
parent
a7493e4279
commit
b5c7bd2d86
@ -1,5 +1,5 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import { Link } from "wouter";
|
||||
import { Search, Play, FileText, ArrowLeft } from "lucide-react";
|
||||
@ -30,6 +30,7 @@ export default function SearchPage() {
|
||||
const initialQuery = new URLSearchParams(qs).get("q") || "";
|
||||
const [query, setQuery] = useState(initialQuery);
|
||||
const [searchTerm, setSearchTerm] = useState(initialQuery);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const q = new URLSearchParams(window.location.search).get("q") || "";
|
||||
@ -39,6 +40,16 @@ export default function SearchPage() {
|
||||
}
|
||||
}, [qs]);
|
||||
|
||||
const handleQueryChange = (val: string) => {
|
||||
setQuery(val);
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => {
|
||||
if (val.trim().length >= 2) {
|
||||
setSearchTerm(val.trim());
|
||||
}
|
||||
}, 500);
|
||||
};
|
||||
|
||||
const { data, isLoading } = useQuery<SearchResult>({
|
||||
queryKey: ["/api/search", searchTerm],
|
||||
queryFn: async () => {
|
||||
@ -53,9 +64,9 @@ export default function SearchPage() {
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
if (query.trim().length >= 2) {
|
||||
setSearchTerm(query.trim());
|
||||
navigate(`/search?q=${encodeURIComponent(query.trim())}`);
|
||||
}
|
||||
};
|
||||
|
||||
@ -78,7 +89,7 @@ export default function SearchPage() {
|
||||
<input
|
||||
type="text"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onChange={(e) => handleQueryChange(e.target.value)}
|
||||
placeholder="Artikel, Videos, Künstler suchen..."
|
||||
className="w-full pl-12 pr-4 py-3 bg-card border border-card-border rounded-lg text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary text-base"
|
||||
autoFocus
|
||||
|
||||
Loading…
Reference in New Issue
Block a user