TanStackT
TanStack3y ago
10 replies
popular-magenta

Using MutationCache to determine if a mutation function should run

I am trying to define a mutationKey in a useMutation hook and use the mutationCache to determine if a mutation has ran before. However, it is not working the way I expect it to work whenever the key changes due to the useMutation never unmounted. I am wondering if there is a better way to do this. This hook is used everywhere in the app so it has to work "globally". Thanks!

const useMutationTrack = (key: string) => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationKey: ['mutations', { key }],
    mutationFn: () => {
      const trackedBefore =
        queryClient.getMutationCache().find({mutationKey:['mutations', { key }]})?.state?.status ===
        'success'
      if (trackedBefore) return Promise.resolve()

      ... other logic
    }
  })
}
Was this page helpful?