framework icon indicating copy to clipboard operation
framework copied to clipboard

Allow debouncing reactive sources in `useFetch`/`useAsyncData`

Open DamianGlowala opened this issue 3 years ago • 4 comments

Environment

n/a

Reproduction

n/a

Describe the bug

Would it be possible to integrate https://vueuse.org/shared/watchdebounced/#watchdebounced with the watch property of useFetch and useAsyncData, so that in addition to being able to pass an array of reactive sources, also make it possible to specify a debounce config for each of them? Currently, given the scenario of a user typing a search query, I cannot find a way to debounce it.

Additional context

No response

Logs

No response

DamianGlowala avatar Jul 11 '22 17:07 DamianGlowala

Would this be something you could implement yourself with a wrapper around useAsyncData, perhaps?

danielroe avatar Jul 12 '22 11:07 danielroe

One of the workarounds is to create an intermediate, debounced and reactive source, as per below:

import { watchDebounced } from '@vueuse/core'

const searchQuery = ref('')
const debouncedSearchQuery = ref('')

watchDebounced(
  searchQuery,
  () => { debouncedSearchQuery.value = searchQuery.value },
  { debounce: 500, maxWait: 1000 },
)

... and then pass debouncedSearchQuery to the watch property of useFetch or useAsyncData.

If this is a recommended and desirable way to approach it, issue can be closed :)

DamianGlowala avatar Jul 12 '22 12:07 DamianGlowala

Just an idea we could also have debouncedRef (either vueuse /cc @antfu or as a nuxt helper). Adding directly to the watch is probably overkill because we cannot tree-shake feature when not needed but seems a legitimate and common usage to have utility and docs for.

pi0 avatar Jul 12 '22 12:07 pi0

Can be done with refDebounced from https://vueuse.org/shared/refDebounced/

import { refDebounced } from '@vueuse/core'

const input = ref('foo')
const debounced = refDebounced(input, 1000)

stafyniaksacha avatar Aug 02 '22 20:08 stafyniaksacha