Spoosh
Plugins

Debounce

Delay requests until input stops changing

The debounce plugin delays requests until the user stops typing or changing input. This prevents excessive API calls during rapid input.

Installation

npm install @spoosh/plugin-debounce

Usage

import { debouncePlugin } from "@spoosh/plugin-debounce";

const plugins = [debouncePlugin()];

// Wait 300ms after typing stops before fetching
const { data } = useRead(
  (api) => api.search.$get({ query: { q: searchTerm } }),
  { debounce: 300 }
);

Conditional Debounce

Only debounce when specific fields change:

const { data } = useRead(
  (api) => api.search.$get({ query: { q: searchTerm, page } }),
  {
    debounce: ({ prevQuery }) => (prevQuery?.q !== searchTerm ? 300 : 0),
  }
);

In this example, debounce is applied when the search query changes, but not when only the page changes.

Options

Per-Request Options

OptionTypeDescription
debouncenumber | (context) => numberMilliseconds to wait, or function for conditional debounce

Debounce Function Context

When using a function, you receive:

PropertyTypeDescription
prevQueryobjectPrevious query parameters
prevBodyunknownPrevious request body
prevParamsobjectPrevious path parameters
prevFormDataobjectPrevious form data

Example: Search Input

function SearchPage() {
  const [searchTerm, setSearchTerm] = useState("");

  const { data, loading } = useRead(
    (api) => api.search.$get({ query: { q: searchTerm } }),
    {
      enabled: searchTerm.length > 0,
      debounce: 300,
    }
  );

  return (
    <div>
      <input
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
        placeholder="Search..."
      />
      {loading && <Spinner />}
      {data?.map((result) => <SearchResult key={result.id} {...result} />)}
    </div>
  );
}

On this page