Handle loading and errors with TanStack Vue Query
After installing @tanstack/vue-query and registering VueQueryPlugin on your Vue app, useQuery() manages request state and caches the result by its query key.
<script setup>
import { useQuery } from '@tanstack/vue-query'
async function fetchPosts() {
const response = await fetch('/api/posts')
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`)
}
return response.json()
}
const { data: posts, isPending, isError, error } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts
})
</script>
<template>
<p v-if="isPending">Loading posts...</p>
<p v-else-if="isError">{{ error.message }}</p>
<ul v-else>
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
</template>
This example uses the v5 API and expects /api/posts to return an array of posts. A failed HTTP response must throw so the query enters its error state.