import React, { useState, useEffect, useRef } from 'react'; import { Helmet } from 'react-helmet'; function Cache() { const [searchQuery, setSearchQuery] = useState(''); const [cacheData, setCacheData] = useState([]); const [keyCount, setKeyCount] = useState(0); const debounceTimeout = useRef(null); // ← store the timeout ID const handleInputChange = (event) => { const query = event.target.value; setSearchQuery(query); // Clear the previous timeout if (debounceTimeout.current) { clearTimeout(debounceTimeout.current); } // Set a new timeout debounceTimeout.current = setTimeout(() => { if (query.trim() !== '') { sendApiCall(query); } else { setCacheData([]); // optional: clear results on empty query } }, 1000); // 2 seconds }; const fetchKeyCount = () => { fetch('/api/cache/keycount') .then((response) => response.json()) .then((data) => { setKeyCount(data.count); }) .catch((error) => { console.error('Error fetching key count:', error); }); }; useEffect(() => { const fetchInterval = setInterval(fetchKeyCount, 10000); fetchKeyCount(); return () => clearInterval(fetchInterval); }, []); const sendApiCall = (text) => { fetch('/api/cache/search', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input: text }), }) .then((response) => response.json()) .then((data) => setCacheData(data)) .catch((error) => console.error('Error:', error)); }; return ( <>
> ); } export default Cache;