UPDATE: Changed Search Bar to use button press instead of debouncing
This commit is contained in:
@@ -1,31 +1,19 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import React, { useState } from "react";
|
||||
import Input from "./Input";
|
||||
import { Search as SearchIcon } from "lucide-react";
|
||||
|
||||
const SearchBar: React.FC = () => {
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [debouncedQuery, setDebouncedQuery] = useState(searchQuery);
|
||||
|
||||
// Debounce the search query
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setDebouncedQuery(searchQuery);
|
||||
}, 500); // Wait 500ms after user stops typing
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [searchQuery]);
|
||||
|
||||
// Perform search when debounced query changes
|
||||
useEffect(() => {
|
||||
if (debouncedQuery.trim()) {
|
||||
const fetchSearchResults = async () => {
|
||||
const handleSearch = async () => {
|
||||
if (searchQuery.trim()) {
|
||||
try {
|
||||
const response = await fetch("/api/search", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ query: debouncedQuery }), // <-- Fixed payload
|
||||
body: JSON.stringify({ query: searchQuery }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
@@ -34,17 +22,19 @@ const SearchBar: React.FC = () => {
|
||||
} catch (error) {
|
||||
console.error("Error performing search:", error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchSearchResults(); // Call the async function
|
||||
}
|
||||
}, [debouncedQuery]);
|
||||
|
||||
};
|
||||
|
||||
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setSearchQuery(e.target.value);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === "Enter") {
|
||||
handleSearch();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div id="search-bar" className="flex items-center">
|
||||
<Input
|
||||
@@ -52,9 +42,9 @@ const SearchBar: React.FC = () => {
|
||||
placeholder="Search..."
|
||||
value={searchQuery}
|
||||
onChange={handleSearchChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
extraClasses="pr-[30px] focus:outline-none focus:border-purple-500 focus:w-[30vw]"
|
||||
/>
|
||||
|
||||
<SearchIcon className="-translate-x-[28px] top-1/2 h-6 w-6 text-white" />
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user