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-debounceUsage
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
| Option | Type | Description |
|---|---|---|
debounce | number | (context) => number | Milliseconds to wait, or function for conditional debounce |
Debounce Function Context
When using a function, you receive:
| Property | Type | Description |
|---|---|---|
prevQuery | object | Previous query parameters |
prevBody | unknown | Previous request body |
prevParams | object | Previous path parameters |
prevFormData | object | Previous 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>
);
}