I’m implementing a search combobox with async results. Here is some sample of code:
export const useTypeahead = () => {
return useLoadableQuery(TypeaheadQuery, {
fetchPolicy: 'network-only',
});
};
// ....
const SearchTypeahead = () => {
const [loadQuery, queryRef, refHandlers] = useTypeahead();
const [query, setQuery] = useState(defaultValue || '');
const debouncedLoad = useDebouncedCallback<typeof loadQuery>((vars) => {
startTransition(() => {
loadQuery(vars);
});
}, 200);
const onQueryChange = (query: string) => {
if (query.length === 0) {
refHandlers.reset();
} else {
debouncedLoad({ query });
}
setQuery(query);
};
// .....
}
As you can see I use debounce and also reset the query as soon as user clears search input. It works fine but I experience the next race condition:
- User types some text
- We send request
- at that moment user immediately clears the input
- we reset
queryRef
- request from step 2 ends and overwrites cache which leads to showing outdated data for cleared text query
So I have two questions:
- Shouldn’t
reset
also abort all ongoing requests? - Is there a way to pass abort signal to
loadQuery
function? As I can see I can only pass it to the hook itself but this way not sure how am I supposed to pass the correct reference to signal
Thanks in advance for any tips