how to trigger vue-query from emit event? #5783
-
Hello, I'm trying to use a vue-query through an emit event from a child component. // App.vue
<script setup lang="ts">
import Layout from "../src/layout/Default.vue";
</script>
<template>
<Layout />
</template>
<style scoped></style> // [Layout] - Default.vue
<script setup lang="ts">
import Main from "../components/Main.vue";
import { useQuery } from "@tanstack/vue-query";
const fetchUsers = async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
return res.json();
};
const clickAPiCall = () => {
const response = useQuery(["users"], fetchUsers);
console.log(response);
};
</script>
<template>
<Main @clickAPiCall="clickAPiCall" />
</template>
<style lang=""></style> // Main.vue
<script setup lang="ts">
const emit = defineEmits(["clickAPiCall"]);
</script>
<template>
<div>Main</div>
<button @click="emit('clickAPiCall')">api Call</button>
</template>
<style scoped></style> When I click the button, the following error occurs. Uncaught Error: vue-query hooks can only be used inside setup() function.
at useQueryClient (useQueryClient.ts:10:11)
at useBaseQuery (useBaseQuery.ts:59:34)
at useQuery (useQuery.ts:171:18)
at clickAPiCall (default.vue:11:20)
at callWithErrorHandling (runtime-core.esm-bundler.js:158:18)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:166:17)
at emit (runtime-core.esm-bundler.js:664:5)
at Proxy.<anonymous> (runtime-core.esm-bundler.js:7422:45)
at _createElementVNode.onClick._cache.<computed>._cache.<computed> (Main.vue:6:19)
at callWithErrorHandling (runtime-core.esm-bundler.js:158:18) I have to trigger vue-query from emit event. How can I get data through vue-query from emit event? Best regards, Jun |
Beta Was this translation helpful? Give feedback.
Answered by
Mini-ghost
Jul 26, 2023
Replies: 1 comment 1 reply
-
You can try this: // [Layout] - Default.vue
<script setup lang="ts">
import Main from "../components/Main.vue";
import { useQuery } from "@tanstack/vue-query";
import { ref } from 'vue'
const fetchUsers = async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
return res.json();
};
const enabled = ref(false)
const { data } = useQuery(["users"], fetchUsers, {
enabled,
})
const clickAPiCall = () => {
enabled.value = true
};
watch(data, (value) => {
console.log(value)
})
</script>
<template>
<Main @clickAPiCall="clickAPiCall" />
</template>
<style lang=""></style> |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
h1jun
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
useQuery
can only be called at the top level ofsetup
function.You can try this: