T
TanStack3y ago
sensitive-blue

Debounce queryFn on useQuery

I'm trying to implement a search component with downshift and tanstack-query. I'm trying to debounce my query function and not my query key as I also need the isLoading state to kick off as the user starts typing, I've had no luck. I've used packages to debounce my queryFn (axios) like lodash debouce, use-debounce but had no luck.
import getFoods from './api' // axios fetcher function, queryFn

export default function Search() {
const { getLabelProps, getInputProps, getMenuProps, isOpen, inputValue } =
useCombobox({
items: [], // needs to be data, how to avoid a circular dependencies?
});
const debouncedGetFoods = debounce(getFoods, 1500); // lodash
const { data, isLoading, refetch } = useQuery(['foods', inputValue], {
queryFn: debouncedGetFoods, // not working
enabled: Boolean(inputValue.trim()),
onSuccess: (data) => console.log('fetched', data),
});

return (
{/* Render logic here */}
<div></div>
)

}
import getFoods from './api' // axios fetcher function, queryFn

export default function Search() {
const { getLabelProps, getInputProps, getMenuProps, isOpen, inputValue } =
useCombobox({
items: [], // needs to be data, how to avoid a circular dependencies?
});
const debouncedGetFoods = debounce(getFoods, 1500); // lodash
const { data, isLoading, refetch } = useQuery(['foods', inputValue], {
queryFn: debouncedGetFoods, // not working
enabled: Boolean(inputValue.trim()),
onSuccess: (data) => console.log('fetched', data),
});

return (
{/* Render logic here */}
<div></div>
)

}
2 Replies
stormy-gold
stormy-gold3y ago
This may help: https://github.com/TanStack/query/issues/293#issuecomment-1308442417 Basically debouncing the query key and comparing the debounced value with the input value to decide on whether to show the loader. Something like :
const showLoader = isLoading || inputValue !== debouncedValue;
const showLoader = isLoading || inputValue !== debouncedValue;
GitHub
Cannot debounce API calls · Issue #293 · TanStack/query
I am trying to use this for a search component, like: const { status, data, error, isFetching } = useQuery( searchQuery &amp;&amp; [&#39;results&#39;, searchQuery], getSearchAsync, ...
deep-jade
deep-jade3y ago
Yeah, I think a comparison between the actual and debounced value is ideal for what you’re describing 👍

Did you find this page helpful?