import { useEffect, useRef, useState } from "react"; import { FaDownload } from "react-icons/fa"; import { toast } from "sonner"; import Container from "../Container"; import NavBar from "../NavBar"; function Cache() { const [searchQuery, setSearchQuery] = useState(""); const [cacheData, setCacheData] = useState([]); const [keyCount, setKeyCount] = useState(0); const [loading, setLoading] = useState(false); const [hasSearched, setHasSearched] = useState(false); const debounceTimeout = useRef(null); // Fetch the key count when the component mounts useEffect(() => { const fetchKeyCount = async () => { try { const response = await fetch("/api/cache/keycount"); const data = await response.json(); setKeyCount(data.count); // Update key count } catch (error) { console.error("Error fetching key count:", error); } }; fetchKeyCount(); }, []); // Run only once when the component mounts const handleInputChange = (event) => { const query = event.target.value; setSearchQuery(query); if (debounceTimeout.current) { clearTimeout(debounceTimeout.current); } if (query.trim() !== "") { setLoading(true); // Show spinner immediately debounceTimeout.current = setTimeout(() => { sendApiCall(query); }, 1000); } else { setHasSearched(false); // Reset state when input is cleared setCacheData([]); } }; const sendApiCall = (text) => { setLoading(true); fetch("/api/cache/search", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ input: text }), }) .then((response) => response.json()) .then((data) => { setCacheData(data); setHasSearched(true); }) .catch((error) => { toast.error(`Error: ${error.message}`); console.error("Error:", error); }) .finally(() => setLoading(false)); }; useEffect(() => { document.title = "Cache | CDRM-Project"; }, []); return ( <> { window.location.href = "/api/cache/download"; }} > Download keys cache {loading ? ( Searching... ) : cacheData.length > 0 ? ( PSSH key ID:key pair {cacheData.map((item, index) => ( {index + 1} {item.PSSH} {item.KID}:{item.Key} ))} ) : hasSearched ? ( No data found in the database ) : ( Enter a search query to see results )} > ); } export default Cache;