简体   繁体   English

如何使 React-Query 突变失效?

[英]How to invalidate from React-Query mutation?

I am trying to refetch a specific data, which should update after a post request in another API.我正在尝试重新获取特定数据,该数据应在另一个 API 中的发布请求后更新。 It's worth mentioning that based on that request two APIs should update and one of them updates, another one not.值得一提的是,基于该请求,两个 API 应该更新,其中一个更新,另一个不更新。

I've tried multiple ways to refetch the API based on successful post request, but nothing seems to work.我已经尝试了多种方法来根据成功的发布请求重新获取 API,但似乎没有任何效果。
I tried to also add 2nd option like this, but without success.我也尝试像这样添加第二个选项,但没有成功。

 {
   refetchInactive: true,
   refetchActive: true,
 }

As it mentioned in this discussion , maybe "keys are not matching, so you are trying to invalidate something that doesn't exist in the cache."正如它在这个讨论中提到的,也许“键不匹配,所以你试图使缓存中不存在的东西无效。” , but not sure that it's my case. ,但不确定这是我的情况。

What is more interesting is that clicking the invalidate button in the devtools, the invalidation per se works.更有趣的是,单击 devtools 中的失效按钮,失效本身就起作用了。

Mutation function:突变 function:

import { BASE_URL, product1Url, product2Url } from './services/api'
import axios from 'axios'
import { useMutation, useQueryClient } from 'react-query'

export const usePostProduct3 = () => {
  const queryClient = useQueryClient()

  const mutation = useMutation(
    async (data) => {
      const url = `${BASE_URL}/product3`
      return axios.post(url, data).then((response) => response)
    },
    {
      onSuccess: async (data) => {
        return (
          await queryClient.invalidateQueries(['prodKey', product1Url]), //this one doesn't work
          queryClient.invalidateQueries(['prodKey', product2Url]) //this api refetch/update works
        )      },
    },
  )

  return mutation
}

What am I doing wrong?我究竟做错了什么?

You shold do it like this你应该这样做

onSuccess:(response)=>{
queryClient.setQueryData("your query key",response.data)

}

Or if you just want to invalidate queries或者,如果您只想使查询无效

import {querCache} from "react-query"
   ...
    onSuccess:(response)=>{
        queryClient.invalidateQueries("your query key")
  
        queryClient.invalidateQueries("your query key")

       //you also can refetch data like this
        queryCache.refetchQueries("your query key")

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM