Simple react debounce fetcher

June 15, 2024ReactProgramming

There will always be the case where I don't want to always fetch each val I typed in input over and over. Imagine I type "bosdk" fast. Then the query will change from "b", to "bo", "bos", "bosd", and "bosdk". This will kick off separate fetches, but there is no guarantee about which order the responses will arrive in.

So, by copying the idea from this page, I want to look cool by pasting it here

const [ Search,setSearch ] = useState( query || "");

useEffect(() => {

const debounce=setTimeout(() => {

if (Search) {

constnewUrl = formURLquery({params : searchParams.toString(),key : "q",value : Search, });

router.push( newUrl, { scroll : false });

} elseif (pathname === route){

const newUrl = removeKeysfromQuery({params : searchParams.toString(),key : ["q"], });

router.push( newUrl, { scroll : false }); } },300);

return () =>clearTimeout( debounce );

}, [Search,router,route,searchParams,query,pathname]);