TanStackT
TanStack4y ago
5 replies
ordinary-sapphire

vue-query hooks can only be used inside setup() function

I have been using solid-query to get effect. Have a project in Vue and wanted to add the Vue version.

Started with

foo.vue
<script setup>
import { useMutation, useQuery, useQueryClient } from "@tanstack/vue-query";

// Access QueryClient instance
const queryClient = useQueryClient();

// Query
const { isLoading, isError, data, error } = useQuery(["todos"], async () => {
  return [{ label: "A" }, { label: "B" }, { label: "C" }];
});

// Mutation
const mutation = useMutation(
  async (args) => {
    console.log("mutation");
  },
  {
    onSuccess: () => {
      // Invalidate and refetch
      queryClient.invalidateQueries(["todos"]);
    },
  }
);

function onButtonClick() {
  mutation.mutate({
    id: Date.now(),
    title: "Do Laundry",
  });
}
</script>

<template>
  <span v-if="isLoading">Loading...</span>
  <span v-else-if="isError">Error: {{ error.message }}</span>
  <!-- We can assume by this point that `isSuccess === true` -->
  <ul v-else>
    <li v-for="todo in data" :key="todo.id">{{ todo.title }}</li>
  </ul>
  <button @click="onButtonClick">Add Todo</button>
</template>


and in main.ts
import { VueQueryPlugin } from "@tanstack/vue-query";
...
app.use(VueQueryPlugin);


But getting vue-query hooks can only be used inside setup() function... I don't know how to proceed
Was this page helpful?