Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 4089

How to call tanstack's vue-query get request inside a method?

$
0
0

I need to query an API as a side-effect of an action and I am trying to use @tanstack/vue-query. Whenever I try to call useQuery inside a function, it throws an error, vue-query hooks can only be used inside setup() function or functions that support injection context.

For example:

api.js

export const getAPIRequest = (url, params={}) => useQuery({    queryKey: [url, params],    queryFn: fetch(url, {        method: 'GET',        headers: {'Content-Type': 'application/json'        },    })})

component.vue

<script setup>const getDetails = () => {    const { data: data } = getAPIRequest('/some-url')    return data}</script><template><button @click="getDetails">Click Here</button></template>

I tried to find a better way to query API from inside a function but I concluded that vue-query can only be called from setup function only. One hack that I came across was answered in this github discussion thread.

Is it true that we can use vue-query only inside setup function? If true, I am not sure how should I structure my project. I have to design side effects that come from button click or typing. Should I move those side effects to POST requests to avoid this situation or is there a better way?

I want to continue using @tanstack/vue-query as it has caching, updating data in background, reactive responses and many more. Is there a better option?


Viewing all articles
Browse latest Browse all 4089

Trending Articles