(+91) 9998562168
Functional IT design
In the Vue world, we don’t really have an opinionated way of how to handle advanced data fetching.
We mostly rely on libraries like Axios to handle the actual creation of the requests, but after that we are left to our own devices in terms of handling how to process that data. There have not been standards for processes beyond fetching, such as caching, synchronizing and updating server state, etc…
Clearly this was not a problem only I was experiencing, and fortunately we now have an exciting tool to turn to that helps us handle more complex and nuanced data-fetching scenarios. The tool is called Vue Query, and in this tutorial we’ll look at what querying crises it helps us solve and explore a working demo of it in action.
The @tanstack/vue-query package offers a 1st-class API for using TanStack Query via Vue.
Consider a “simple” task from your product team: Display a list of users from the database.
At first, you may think that you could just:
Easy enough, right?
But what happens once you get past the MVP?
What if that “simple” poll eventually requires pagination, or infinite-scroll loading, or automatic refetching to avoid stale data, or caching, or how about setting the retrieved data as part of a global state that should be smart enough not to re-fetch unless it’s been a while since the last poll?
Now our simple data-fetching task just became a lot more work.
We’re starting to touch on the scenarios where Tanstack’s Query for Vue comes to the rescue.
According to the website’s overview, Vue Query helps us with:
A very common approach to solve all of these and more is to use GraphQL and Apollo. But realistically, it’s not always possible to implement or rewrite your backend just to be able to use GraphQL in your frontend.
The beauty of Tanstack Query is that it is completely agnostic about how you interact with your API. The only thing it needs is for you to provide it with a function that returns a Promise. This function can internally be using Axios, fetch, or whatever other solution you currently already have in place. You don’t even need to refactor most of your code to use it.
At this point you may be wondering if Tanstack Query is hard to learn or difficult to use. I’m happy to share with you that its not! With a very gentle learning curve, opinionated but sensible defaults, and clear documentation I was able to go from getting my team’s buy-in to production in less than a month (granted we haven’t replaced every single piece of data fetching with it, but you also probably shouldn’t).