useDebounce()
Delays updating the parameters by debouncing.
Useful to avoid spamming network requests when parameters might change quickly (like a typeahead field).
tip
useDebounce() returns refs, so the debounced
value can be passed directly to other composables or components. isPending is true from the moment
the input changes until the debounced value is updated.
Usage
resources/Issue
IssueList.vue
SearchIssues.vue
<script setup lang="ts"> import { onErrorCaptured, ref } from 'vue'; import { useDebounce } from '@data-client/vue'; import IssueList from './IssueList.vue'; const query = ref(''); // highlight-next-line const [debouncedQuery, isPending] = useDebounce(query, 200); const input = ref<HTMLInputElement>(); function clear() { query.value = ''; input.value?.focus(); } const error = ref<Error | null>(null); onErrorCaptured(e => { error.value = e; return false; }); </script> <template> <header class="appHeader"> <h1 class="appTitle">Issues</h1> </header> <label class="search" :aria-busy="isPending"> <input ref="input" v-model="query" type="search" aria-label="Search issues" placeholder="Search issues" /> <button type="button" class="clear" aria-label="Clear search" @click="clear" /> </label> <ErrorMessage v-if="error" :error="error" :resetErrorBoundary="() => (error = null)" /> <Suspense v-else> <IssueList :search="debouncedQuery" :stale="isPending" /> <template #fallback><Loading /></template> </Suspense> </template>
Types
function useDebounce<T>(
value: T | Ref<T>,
delay: number,
updatable?: boolean | Ref<boolean>,
): [Ref<T>, Ref<boolean>];
value and updatable can be plain values or refs.
Returns a tuple of [debouncedValue, isPending] refs. When updatable is false, the debounced
value stops updating and isPending resets to false.