Vue.js is a popular JavaScript framework for building user interfaces and single-page applications. One of the key features of Vue.js is its simplicity and ease of use, making it an excellent choice for beginners and experienced developers alike. In this tutorial, we will be focusing on a library called Tanstack Vue Query, which provides a set of tools for managing data in Vue.js applications.
What is Tanstack Vue Query?
Tanstack Vue Query is a library that provides a simple and efficient way to fetch and manage data in Vue.js applications. It is built on top of the Vue.js composition API, which allows you to write more organized and maintainable code. With Tanstack Vue Query, you can easily fetch and cache data from APIs, update data in real-time, and handle complex data requirements with ease.
Installing Tanstack Vue Query
To get started with Tanstack Vue Query, you will need to install the library using npm or yarn. Open your terminal and run the following command:
npm install @tanstack/vue-query
or
yarn add @tanstack/vue-query
Using Tanstack Vue Query in Your Vue.js Application
Once you have installed Tanstack Vue Query, you can start using it in your Vue.js application. To do this, you will need to create a new instance of the QueryClient
class and provide it to your Vue app. Here’s an example of how you can set up Tanstack Vue Query in your main.js file:
import { createApp } from 'vue'
import App from './App.vue'
import { QueryClient, createVuePlugin } from '@tanstack/vue-query'
const queryClient = new QueryClient()
createApp(App)
.use(createVuePlugin(queryClient))
.mount('#app')
In this example, we are creating a new instance of the QueryClient
class and passing it to the createVuePlugin
function to create a Vue plugin. We then use the .use()
method to register the plugin with our Vue app.
Fetching Data with Tanstack Vue Query
Once you have set up Tanstack Vue Query in your Vue.js application, you can start fetching data from APIs using the useQuery
hook. Here’s an example of how you can fetch data from a REST API using useQuery
:
import { useQuery } from '@tanstack/vue-query'
export default {
setup() {
const query = useQuery('todos', async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/todos')
return response.json()
})
return {
todos: query.data
}
}
}
In this example, we are using the useQuery
hook to fetch data from the JSONPlaceholder API and store it in the todos
variable. The useQuery
hook takes two arguments: a unique key for the query and an asynchronous function that fetches the data.
Displaying Data in Your Vue.js Application
Once you have fetched data using Tanstack Vue Query, you can display it in your Vue.js application using the data returned by the useQuery
hook. Here’s an example of how you can display a list of todos in your Vue component:
<template>
<div>
<ul>
<li v-for="todo in todos" :key="todo.id">{{ todo.title }}</li>
</ul>
</div>
</template>
<script>
import { useQuery } from '@tanstack/vue-query'
export default {
setup() {
const query = useQuery('todos', async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/todos')
return response.json()
})
return {
todos: query.data
}
}
}
</script>
In this example, we are using the v-for
directive to loop through the todos
array and display each todo item in a list. The :key
attribute is used to provide a unique key for each todo item.
Updating Data in Real-Time with Tanstack Vue Query
One of the key features of Tanstack Vue Query is its ability to update data in real-time. You can achieve this by using the useMutation
hook to send updates to the server and then updating the data in the cache. Here’s an example of how you can update a todo item in your Vue component:
<template>
<div>
<ul>
<li v-for="todo in todos" :key="todo.id">
{{ todo.title }}
<button @click="toggleComplete(todo)">Toggle complete</button>
</li>
</ul>
</div>
</template>
<script>
import { useQuery, useMutation } from '@tanstack/vue-query'
export default {
setup() {
const query = useQuery('todos', async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/todos')
return response.json()
})
const updateTodo = useMutation('updateTodo', (updatedTodo) => {
// Update the todo item in the cache
query.setData(updatedTodo.id, updatedTodo)
})
const toggleComplete = (todo) => {
const updatedTodo = { ...todo, completed: !todo.completed }
updateTodo.mutate(updatedTodo)
}
return {
todos: query.data,
toggleComplete
}
}
}
</script>
In this example, we are using the useMutation
hook to update a todo item in the cache when the user clicks on the "Toggle complete" button. The updateTodo
mutation takes the updated todo item as an argument and updates the data in the cache using the setData
method.
Handling Complex Data Requirements with Tanstack Vue Query
Tanstack Vue Query provides a set of tools for handling complex data requirements in Vue.js applications, such as pagination, real-time updates, and optimistic updates. You can achieve this by using the usePaginatedQuery
and useMutation
hooks in combination with the QueryClient
class. Here’s an example of how you can implement pagination in your Vue component:
<template>
<div>
<ul>
<li v-for="todo in todos" :key="todo.id">{{ todo.title }}</li>
</ul>
<button @click="loadMore">Load more</button>
</div>
</template>
<script>
import { usePaginatedQuery, QueryClient } from '@tanstack/vue-query'
const queryClient = new QueryClient()
export default {
setup() {
const query = usePaginatedQuery('todos', async ({ pageParam = 1 }) => {
const response = await fetch(`https://jsonplaceholder.typicode.com/todos?_page=${pageParam}`)
return response.json()
})
const loadMore = () => {
query.fetchNextPage()
}
return {
todos: query.data.pages.flatMap(page => page.results),
loadMore
}
}
}
</script>
In this example, we are using the usePaginatedQuery
hook to fetch data from a paginated API and display it in a list. The fetchNextPage
method is used to load more data when the user clicks on the "Load more" button.
Conclusion
In this tutorial, we have covered the basics of using Tanstack Vue Query in your Vue.js applications. With Tanstack Vue Query, you can easily fetch and manage data, update data in real-time, and handle complex data requirements with ease. We have also explored how to set up Tanstack Vue Query, fetch data from APIs, display data in your Vue.js application, update data in real-time, and handle complex data requirements such as pagination. I hope this tutorial has been helpful in getting you started with Tanstack Vue Query and building robust Vue.js applications. Happy coding!
Super!! super!! J'utilisais sans connaitre la puissance du truc.
Merci !!!
Merci Gafikart pour ton travail remarquable et ta pedagogie.
Jusqu'ici j'utilisais Pinia pour la gestion des states mais mon appli prends enormement de temps à charger au fil du temps et chose qui m'a poussé à fouiller comment remedier cela.
Je suis tomber sur Tanstack query mais qui en gros change un peu la structure du code.
J'aime bien le decoupage et la centralisation de concern de PINIA alors ma question est de savoir est-il possible de combiner vuequery et pinia ?
si oui, ça serait vraiment génial de nous faire une vidéo sur le sujet.
Comme vous êtes occupé, avez-vous un lien qui explique célà ?
Merci d'avance. Je vous suis dépuis mes début dans le code en 2020, vous êtes un HERO pour moi. 🫡
Est-ce que ceci vient remplacer Pinia ou est-ce que les deux sont complémentaires ?
Juste 🎉
hello, merci pour ce tuto très clair comme d’habitude ! je vois que tu as un raccourci clavier pour auto importer les libs utilisés dans le code,
peux-tu nous partager cette astuce / ce raccourci stp ? 🙏🏻
que pense tu de filamentphp?
très bon tuto. Merci