T
TanStack3y ago
ambitious-aqua

Refecth using cache instead execute queryFn

It is possible to "refetch" withouth execute queryFn when is on cache? this is my simply code:
import axios from 'axios';
import { AjaxResponse, AvailableSelect } from '@/types';
import { ajaxAvailableSelect } from '@/configurationType';
import { useQuery } from '@tanstack/vue-query'
import { Ref, watch } from 'vue';

export const useGetAvailableSelectList = (id_available_select_type: Ref<string>) => {

const queryFn = (): Promise<Array<Partial<AvailableSelect>>> => {
return new Promise((resolve, reject) => {
console.log('fetching')
if (!id_available_select_type.value) return resolve([])

return axios.get<AjaxResponse<Array<AvailableSelect>>>(ajaxAvailableSelect, {
params: {
id_available_select_type: id_available_select_type.value
}
})
.then((response) => {
if (response.data.success) {
resolve(response.data.data)
} else {
reject('Error')
}
})
.catch(reject)
})
};

const { data, refetch } = useQuery(
['availableSelect', id_available_select_type.value], {
queryFn,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
enabled: false,
initialData: []
});

watch(
() => id_available_select_type.value, // detect id is changed to request new data if is not in cache
(newId) => {
console.log('detectedNewId', newId)
refetch() // request data
})


return data;
};
import axios from 'axios';
import { AjaxResponse, AvailableSelect } from '@/types';
import { ajaxAvailableSelect } from '@/configurationType';
import { useQuery } from '@tanstack/vue-query'
import { Ref, watch } from 'vue';

export const useGetAvailableSelectList = (id_available_select_type: Ref<string>) => {

const queryFn = (): Promise<Array<Partial<AvailableSelect>>> => {
return new Promise((resolve, reject) => {
console.log('fetching')
if (!id_available_select_type.value) return resolve([])

return axios.get<AjaxResponse<Array<AvailableSelect>>>(ajaxAvailableSelect, {
params: {
id_available_select_type: id_available_select_type.value
}
})
.then((response) => {
if (response.data.success) {
resolve(response.data.data)
} else {
reject('Error')
}
})
.catch(reject)
})
};

const { data, refetch } = useQuery(
['availableSelect', id_available_select_type.value], {
queryFn,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
enabled: false,
initialData: []
});

watch(
() => id_available_select_type.value, // detect id is changed to request new data if is not in cache
(newId) => {
console.log('detectedNewId', newId)
refetch() // request data
})


return data;
};
Or maybe that can be done native?
2 Replies
ambitious-aqua
ambitious-aquaOP3y ago
I see the issue comes of "staleTime: Infinity," when is actived they dont refecth when id changes
wise-white
wise-white3y ago
Your query key must use the ref directly. You should not call .value on it

Did you find this page helpful?