reactive key and caching #6908
-
hey all, Can somebody shed some light about using the cache, when dealing with a reactive parameter in the queryKey? For me it seems caching is not working at all, in that case <script setup lang="ts">
import { computed, ref } from 'vue';
import { useQuery, useQueryClient } from 'vue-query';
const productId = ref(0);
const queryClient = useQueryClient();
const { data: product } = useQuery({
queryKey: ['product', productId],
queryFn: (context) => {
const previousData = queryClient.getQueryData(context.queryKey);
if (previousData) {
console.warn('previously loaded', productId.value);
// why wasn't this returned from cache, instead of calling the queryFn again for this id?
}
console.warn('go load ', productId.value);
return Promise.resolve({id: productId.value})
},
enabled: computed(() => productId.value > 0),
});
const changeProduct = (newId: number) => {
productId.value = newId;
}
</script>
<template>
loaded: {{ product?.id }}
<button @click="changeProduct(1)">load 1</button>
<button @click="changeProduct(2)">load 2</button>
<button @click="changeProduct(3)">load 3</button>
</template> In the above example, for me the queryFn is always executed, even if the query client has cached data for this key. Everything works as expected when not using reactive params in the queryKey. global config: const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClientConfig: {
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
refetchOnMount: false,
retry: 0,
},
},
},
}; |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
In vue-query you can instruct the library to never automatically refetch data it has already cached using |
Beta Was this translation helpful? Give feedback.
-
You are confusing When you previously fetched the query with a given key, and you use it again before it gets garbage collected, you will just get You do not have to access If you want to avoid refetch in the background, set higher
You might also want to leverage |
Beta Was this translation helpful? Give feedback.
-
Yes thanks, setting the |
Beta Was this translation helpful? Give feedback.
In vue-query you can instruct the library to never automatically refetch data it has already cached using
staleTime: Infinity
. This means that once the library successfully fetches data for a specific query key, it will always return that cached data for subsequent requests with the same key.