I have this component in Vue.
When I save, the server is returning the updated record. So, I don't need to hit the server with yet another request.
However, this is triggering the new get:
我在Vue有这个组件。当我保存时,服务器将返回更新的记录。因此,我不需要再向服务器发送另一个请求。然而,这触发了新的GET:
queryClient.invalidateQueries({ queryKey: ['projects'] })
I am new to vue-query. I realise the cache needs to be invalidated. However... is there any way to prevent another reload when it's invalidated?
我是VUE-QUERY的新手。我意识到缓存需要作废。然而.。当它失效时,有没有办法防止另一次重新加载?
<script setup>
import { useDataLoader } from '../lib/dataLoader.js'
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useQuery, useQueryClient, useMutation } from "@tanstack/vue-query";
const route = useRoute()
const api = useDataLoader('projects', { baseUrl: '/stores/1.0.0'})
let record = ref({})
const { isLoading, isFetching, isError, data, error, refetch } = useQuery({
queryKey: ['projects', route.params.id],
queryFn: () => api.get(route.params.id).then(data => record.value = data),
})
watch(() => route.params.id, () => { refetch() })
// Access QueryClient instance
const queryClient = useQueryClient()
const mutation = useMutation({
mutationFn: (record) => api.put(route.params.id, record).then(data => record.value = data),
onSuccess: (record) => {
record.value = record
// Invalidate and refetch
queryClient.invalidateQueries({ queryKey: ['projects'] })
},
})
function save (e) {
const data = Object.fromEntries(new FormData(e.target))
/* Change data here if necessary */
mutation.mutate(data)
}
</script>
<template>
<h1>Edit Project</h1>
<form @submit.prevent="save">
<input name="name" :value="record.name" :id="record.id">
<input type="submit" value="Save">
</form>
</template>
<style>
</style>
更多回答
优秀答案推荐
Nevermind sorry.
不要紧,对不起。
When dealing with mutations that update objects on the server, it's common for the new object to be automatically returned in the response of the mutation. Instead of refetching any queries for that item and wasting a network call for data we already have, we can take advantage of the object returned by the mutation function and update the existing query with the new data immediately using the Query Client's setQueryData method:
更多回答
我是一名优秀的程序员,十分优秀!