Johnny Kontrolletti
Johnny Kontrolletti

Reputation: 899

Debounce won't execute request max once per second

I have the following component handling a text search. To reduce requests I'm trying to debounce my handler. My goal is to execute one request maximum every second.

The following code executes the handler on every single re-render of value, but with an initial delay of 1000ms. AFAIK a debounce means that for f.i. hello, the request won't be executed for every single character, but max once per second, right?

What am I doing wrong?

const [value, setValue] = useState<string>("");

useEffect(() => {
    handleQuery();
}, [value]);

const handleQuery = debounce(() => {
    console.log(value);
}, 1000);

return (
    <SearchWrapper>
        <SearchBar value={value} onInput={setValue} />
    </SearchWrapper>
);

Upvotes: 0

Views: 525

Answers (1)

Ryan Le
Ryan Le

Reputation: 8412

You don't actually need a useEffect before debouncing an action:

Try to change to something like this:

const [value, setValue] = useState<string>("");

const handleQuery = debounce((searchText) => {
  console.log(searchText);
}, 1000);

return (
  <SearchWrapper>
    <SearchBar
      value={value}
      onInput={(searchText) => {
        setValue(searchText);
        handleQuery(searchText);
      }}
    />
  </SearchWrapper>
);

Upvotes: 1

Related Questions