Để triển khai tính năng tự động re-fetch sau khi thực hiện mutation ở trong React Query, ta cần dùng hook useQueryClient từ @tanstack/react-query:

import { useQueryClient } from "@tanstack/react-query"

Tạo ra một query client thông qua hook trên:

const queryClient = useQueryClient()

Gọi sử dụng phương thức invalidateQueries của query client với đối số là key của query để triển khai automated re-fetching.

Ví dụ bên dưới thực hiện invalidate query có key là ["products", productId] khi mutation request được thực hiện thành công:

const updateProductPriceMutation = useMutation({
  // ...
  onSuccess: ({ productId }) => {
    queryClient.invalidateQueries(["products", productId])
  },
})

Đối số thứ hai của phương thức invalidateQueries là một object chứa các option. Trong số đó, option exact giúp chỉ định chính xác query key nào sẽ bị invalidate.

Ví dụ:

const createProductMutation = useMutation({
  // ...
  onSuccess: ({ productId }) => {
    queryClient.invalidateQueries(["products"], { exact: true })
  },
})

Trong ví dụ trên, chỉ những query nào có key là ["products"] thì mới bị invalidate. Các query mà có key bắt đầu bằng ["products"] chẳng hạn như ["products", productId] sẽ không bị ảnh hưởng.

Resources