How to create debounce search with tRPC

So I'm aware that react-query provides a useDebounce hook but I guess tRPC doesn't wrap around this - so I'm wondering, what is the optimal way to create a simple search bar function with tRPC? If I have something like this:
const { data } = api.users.getById.useQuery({ id });
const { data } = api.users.getById.useQuery({ id });
How do I add debouncing functionality so that the query only fires after a set time interval? As far as I can tell, tRPC queries fire instantly unless you set the
enabled
enabled
property, but that only accepts a boolean.
3 Replies
Endgame1013
Endgame101316mo ago
I think the way to do this would be to use a useDebounce hook and use the “enabled” option in the useQuery hook. https://dev.to/gabe_ragland/debouncing-with-react-hooks-jci
DEV Community
Debouncing with React Hooks
Easily debounce any fast changing value to ensure expensive operations are not executed too frequently.
Endgame1013
Endgame101316mo ago
So that might look something like this: const [search, setSearch] = useState(“”) const debouncedSearch = useDebounce(search, 500) const { data } = api.example.useQuery({ name: debouncedSearch }, { enabled: debouncedSearch.length > 0 }) One word of caution, though. I’ve noticed that isLoading doesn’t really behave the way you’d expect when using the “enabled” option. I think you can work around that like this: https://github.com/TanStack/query/issues/3584#issuecomment-1369491188
GitHub
[Beta] Disabled query has isLoading: true property · Issue #3584 ...
Describe the bug In react-query@beta version has strange behaviour. By default query that has enabled: false option has isLoading: true property (see code sandbox for details). In stable release re...
zendev
zendevOP16mo ago
Thanks for your help! Will try this out and let you know.
Want results from more Discord servers?
Add your server