MutationCache 是用於儲存 mutations 的儲存空間。
通常情況下,您不會直接與 MutationCache 互動,而是使用 QueryClient。
import { MutationCache } from '@tanstack/react-query'
const mutationCache = new MutationCache({
onError: (error) => {
console.log(error)
},
onSuccess: (data) => {
console.log(data)
},
})
import { MutationCache } from '@tanstack/react-query'
const mutationCache = new MutationCache({
onError: (error) => {
console.log(error)
},
onSuccess: (data) => {
console.log(data)
},
})
它提供的方法有:
選項
MutationCache 上的 onError、onSuccess、onSettled 和 onMutate 回呼函式可用於在全域層級處理這些事件。它們與提供給 QueryClient 的 defaultOptions 不同,原因如下:
getAll 會回傳快取中的所有 mutations。
注意:大多數應用程式通常不需要使用此方法,但在罕見情況下需要獲取有關 mutation 的更多資訊時,它會派上用場。
const mutations = mutationCache.getAll()
const mutations = mutationCache.getAll()
回傳值
subscribe 方法可用於訂閱整個 mutation 快取,並在快取發生安全/已知的更新時(如 mutation 狀態變更或 mutations 被更新、新增或移除)收到通知。
const callback = (event) => {
console.log(event.type, event.mutation)
}
const unsubscribe = mutationCache.subscribe(callback)
const callback = (event) => {
console.log(event.type, event.mutation)
}
const unsubscribe = mutationCache.subscribe(callback)
選項
回傳值
clear 方法可用於完全清除快取並重新開始。
mutationCache.clear()
mutationCache.clear()