Vue Query - Data Fetching Hooks

1.26.0 · active · verified Sun Apr 19

Vue Query is a library designed to simplify data fetching, caching, and synchronization for Vue applications, bringing the powerful features of TanStack Query (formerly React Query) to the Vue ecosystem. It provides a set of hooks for declarative and efficient management of asynchronous data, reducing boilerplate and improving developer experience. The current stable version is 1.26.0, but version 2.x is under active beta development, which tightly aligns its core logic with `@tanstack/query-core`. This alignment in v2 is a key differentiator, ensuring consistency with the broader TanStack Query ecosystem. It addresses common challenges like caching, background refetching, optimistic updates, and pagination out-of-the-box, making it an advanced solution compared to manual `fetch` or `axios` implementations. The library is actively maintained with ongoing feature development and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `vue-query` in a Vue 3 application. It initializes a `QueryClient`, provides it via `QueryClientProvider`, and then uses `useQuery` within a component to fetch and display data from a public API, handling loading and error states.

import { createApp, defineComponent } from 'vue';
import { QueryClient, QueryClientProvider, useQuery } from 'vue-query';

const queryClient = new QueryClient();

const fetchTodos = async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};

const App = defineComponent({
  name: 'App',
  setup() {
    const { data, isLoading, isError, error } = useQuery('todo', fetchTodos);

    return {
      data,
      isLoading,
      isError,
      error,
    };
  },
  template: `
    <div>
      <h1>My Todo</h1>
      <p v-if="isLoading">Loading todo...</p>
      <p v-else-if="isError">Error: {{ error.message }}</p>
      <div v-else>
        <p>ID: {{ data.id }}</p>
        <p>Title: {{ data.title }}</p>
        <p>Completed: {{ data.completed ? 'Yes' : 'No' }}</p>
      </div>
    </div>
  `,
});

const app = createApp({
  render() {
    return [
      h(QueryClientProvider, { client: queryClient }, {
        default: () => h(App)
      })
    ];
  }
});
app.mount('#app');

view raw JSON →