What is @tanstack/vue-query?
@tanstack/vue-query is a powerful data-fetching and state management library for Vue.js applications. It provides tools to fetch, cache, synchronize, and update server state in your application, making it easier to manage asynchronous data and improve the user experience.
What are @tanstack/vue-query's main functionalities?
Data Fetching
This feature allows you to fetch data from an API and manage the loading, error, and success states. The `useQuery` hook is used to fetch data and automatically cache it.
```javascript
import { useQuery } from '@tanstack/vue-query';
const fetchTodos = async () => {
const response = await fetch('/api/todos');
return response.json();
};
export default {
setup() {
const { data, error, isLoading } = useQuery(['todos'], fetchTodos);
return { data, error, isLoading };
}
};
```
Data Mutation
This feature allows you to perform mutations (create, update, delete) on your data. The `useMutation` hook is used to handle the mutation and automatically update the cache.
```javascript
import { useMutation, useQueryClient } from '@tanstack/vue-query';
const addTodo = async (newTodo) => {
const response = await fetch('/api/todos', {
method: 'POST',
body: JSON.stringify(newTodo),
});
return response.json();
};
export default {
setup() {
const queryClient = useQueryClient();
const mutation = useMutation(addTodo, {
onSuccess: () => {
queryClient.invalidateQueries(['todos']);
},
});
return { mutation };
}
};
```
Query Invalidation
This feature allows you to manually invalidate queries, which forces them to refetch. This is useful when you know that the data has changed and you want to ensure that your UI is up-to-date.
```javascript
import { useQueryClient } from '@tanstack/vue-query';
export default {
setup() {
const queryClient = useQueryClient();
const invalidateTodos = () => {
queryClient.invalidateQueries(['todos']);
};
return { invalidateTodos };
}
};
```
Query Caching
This feature allows you to cache query results for a specified amount of time. The `staleTime` option is used to determine how long the data is considered fresh before it needs to be refetched.
```javascript
import { useQuery } from '@tanstack/vue-query';
const fetchUser = async (userId) => {
const response = await fetch(`/api/user/${userId}`);
return response.json();
};
export default {
setup() {
const { data, error, isLoading } = useQuery(['user', userId], () => fetchUser(userId), {
staleTime: 1000 * 60 * 5, // 5 minutes
});
return { data, error, isLoading };
}
};
```
Other packages similar to @tanstack/vue-query
vue-apollo
Vue Apollo integrates GraphQL into your Vue.js applications. It provides a declarative way to fetch and manage GraphQL data, similar to how @tanstack/vue-query handles RESTful data fetching. However, vue-apollo is specifically designed for GraphQL APIs.
axios
Axios is a popular HTTP client for making requests to APIs. While it does not provide the same level of state management and caching as @tanstack/vue-query, it is often used in conjunction with Vue.js to handle data fetching.
vue-resource
Vue Resource is an HTTP client for Vue.js that provides services for making web requests and handling responses. It is similar to axios but is specifically designed for Vue.js. It lacks the advanced caching and state management features of @tanstack/vue-query.
Vue Query
Hooks for fetching, caching and updating asynchronous data in Vue.
Support for Vue 2.x via vue-demi
Documentation
Visit https://tanstack.com/query/latest/docs/vue/overview
Quick Features
- Transport/protocol/backend agnostic data fetching (REST, GraphQL, promises, whatever!)
- Auto Caching + Refetching (stale-while-revalidate, Window Refocus, Polling/Realtime)
- Parallel + Dependent Queries
- Mutations + Reactive Query Refetching
- Multi-layer Cache + Automatic Garbage Collection
- Paginated + Cursor-based Queries
- Load-More + Infinite Scroll Queries w/ Scroll Recovery
- Request Cancellation
- (experimental) Suspense + Fetch-As-You-Render Query Prefetching
- (experimental) SSR support
- Dedicated Devtools
- (depending on features imported)
Quick Start
-
Install vue-query
$ npm i @tanstack/vue-query
or
$ pnpm add @tanstack/vue-query
or
$ yarn add @tanstack/vue-query
or
$ bun add @tanstack/vue-query
If you are using Vue 2.6, make sure to also setup @vue/composition-api
-
Initialize Vue Query via VueQueryPlugin
import { createApp } from 'vue'
import { VueQueryPlugin } from '@tanstack/vue-query'
import App from './App.vue'
createApp(App).use(VueQueryPlugin).mount('#app')
-
Use query
import { defineComponent } from 'vue'
import { useQuery } from '@tanstack/vue-query'
export default defineComponent({
name: 'MyComponent',
setup() {
const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })
return {
query,
}
},
})
-
If you need to update options on your query dynamically, make sure to pass them as reactive variables
const id = ref(1)
const enabled = ref(false)
const query = useQuery({
queryKey: ['todos', id],
queryFn: () => getTodos(id),
enabled,
})