wess
wess6d ago

debouncing

hey! i have a text input and based on its value i need to query the database? right now as soon as i type something it starts to query and is being super reactive. which is good, but at the same time "isn't it putting too much pressure on db"? and hence increasing the total costs for me? should i implement a debouncing on the client side for that? if yes -- then whats is the best way to do that? because its returning immediately results for previous debounced value -- which is wrong and staying like that for some time until the next debounced value appears
10 Replies
Convex Bot
Convex Bot6d ago
Thanks for posting in <#1088161997662724167>. Reminder: If you have a Convex Pro account, use the Convex Dashboard to file support tickets. - Provide context: What are you trying to achieve, what is the end-user interaction, what are you seeing? (full error message, command output, etc.) - Use search.convex.dev to search Docs, Stack, and Discord all at once. - Additionally, you can post your questions in the Convex Community's <#1228095053885476985> channel to receive a response from AI. - Avoid tagging staff unless specifically instructed. Thank you!
ballingt
ballingt6d ago
@wess have you used React for other things before? I'd do this with a debounce hook, something like https://usehooks.com/usedebounce
wess
wessOP6d ago
yes sure, using that exactly
ballingt
ballingt6d ago
and use the non-reactive version of useQuery, convex.query:
const convex = useConvex()
const convexSearch = useCallack(() => {
return convex.query(api.search.doTheSearch, {});
}, );
const debouncedConvexSearch = useDebounce(convexSearch)
const convex = useConvex()
const convexSearch = useCallack(() => {
return convex.query(api.search.doTheSearch, {});
}, );
const debouncedConvexSearch = useDebounce(convexSearch)
Or you could do this with a setState and still use the useQuery
const [debouncedQuery, setDebouncedQuery] = useState();
const handleInputChange = useDebounce(setDebouncedQuery)
const results = useQuery(api.search.doSearch, {query: debouncedQuery});
const [debouncedQuery, setDebouncedQuery] = useState();
const handleInputChange = useDebounce(setDebouncedQuery)
const results = useQuery(api.search.doSearch, {query: debouncedQuery});
wess
wessOP6d ago
thanks, will give it a try
ballingt
ballingt6d ago
sounds like we shoudl have a recipe for this
ballingt
ballingt6d ago
Help, my app is overreacting!
Reactive backends like Convex make building live-updating apps a cinch, but default behavior might be too reactive for some use cases. Not to worry! L...
ballingt
ballingt6d ago
oh wait this is perfect
wess
wessOP6d ago
yeah this is helpful thx
ian
ian5d ago
Throttling Requests by Single-Flighting
For write-heavy applications, use single flighting to dynamically throttle requests. See how we implement this with React hooks for Convex.