Simple react debounce fetcher

July 24, 2022reacttip slips

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 "penis" fast. Then the query will change from "p", to "pe", "pen", "peni", and "penis". 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

import React, { useEffect, useState } from 'react';

const fakeFetch = (time) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), time)
  })
}

export function App(props) {
  const [results, setResults] = useState();
  const [val, setVal] = useState('')


  useEffect(() => {
    let ignore = false;

    fakeFetch(2000).then(json => {
        if (!ignore) {
            setResults(json)
        }
    });


    return () => { ignore = true; };
  }, [val]);


  return (
    <input value={val} onChange={e => setVal(e.target.value)} />
  );
}