Query on user action while respecting cache
Hi everyone !
I'm trying out Vue (Nuxt) and tanstack query currently, and I'm trying to create a query that only fetch data when a user makes an action (ex: a search when the user click on a submit button). For that, I use
enable: false
and the refetch()
method, but, unless I'm mistaken, this method ignore the cache and the request is fired every time. Is there a way to make it work ?4 Replies
fair-rose•3y ago
Could you please explain what are you trying to achieve?
If user is entering some data, then include this data in the queryKey and potentially enable query conditionally based on this input.
puzzled-coralOP•3y ago
Hi ! I managed to make it work with intermediate states.
The idea was to fire queries only on user action while keeping the cache feature. For example, if I have a search bar with a text input and a submit button, if I link the query key to the input ref value, it would fire every time the value changes. So I first disabled the query and used query.refetched() in the submit method to trigger it, but this was ignoring the cache and the request was made even if the input ref value was the same. Finaly, I made an intermediate ref used in the query key that would be updated when the submit method is executed (without the refetch()) and it works as intended. The only downside is that for complex queries that depend on different actions, it needs multiple intermediate states.
fair-rose•3y ago
So usually search is implemented as
debounce
. Meaning that until user stops typing, search would not be triggered. Then you include search string in query key and you should have robust search functionality that does not require to click a button but still does not fetch too often.
If you really must to fetch only on the button click, add one more search ref (searchParam, searchTemp) and on click just copy string from temp
to param
. It adds just one more ref, so it should be pretty easy to reason about as well.puzzled-coralOP•3y ago
It depends of what you want to do. The example I gave (which is a simplified version of what I needed) is similar to the search bar of Google, you don't want an automatic query for this.
What you suggested after is what I ended up implementing. But I think it would be nice to have the refetch method to have an option to use the cache if available for use cases like this one.