在 React 中的本地状态更改后重新获取查询的语法是什么

What is the Syntax for Refetching a Query after a Local State Change in React

我对 Apollo 和 GraphQL 比较陌生,我需要在几次突变后重新查询,因为反冲状态不想及时更新,并且在一些突变后会抛出一百万个错误。我只是不知道如何执行此操作,并且无法找到与我的场景相关的任何文档。 以下代码在App.js 文件中。

// Mutations
  const { loading: loadingO, error: errorO, data: dataO, refetch: refetchO } = useQuery(GET_OWNER)
  const { loading: loadingM, error: errorM, data: dataM, refetch: refetchM } = useQuery(GET_MANAGER)

  const handleRefresh = () => {
    setRefresh(!refresh)
    if (role && id){
      if (role == "MANAGER"){
        // reftechM
      }
      if (role == "OWNER"){
        // refetchO
      }
    }
  }

  useEffect( () => {
    console.log("???")
  }, [refetchM, refetchO])

...其中 handleRefresh 本质上是在每次突变之后,或者当然是每次刷新之后调用的。但是,仅调用 refetch 是行不通的,而且我一直找不到适合我的问题的语法。有人知道解决办法吗?

直接从 apollo 文档试试这个:

Refetching queries after a mutation

In certain cases, writing an update function to update the cache after a mutation can be complex, or even impossible if the mutation doesn't return modified fields.

In these cases, you can provide a refetchQueries option to the useMutation hook to automatically rerun certain queries after the mutation completes.

For details, see Refetching queries.

Note that although refetchQueries can be faster to implement than an update function, it also requires additional network requests that are usually undesirable. For more information, see this blog post."

来源:https://www.apollographql.com/docs/react/caching/advanced-topics/

默认情况下,useQuery 挂钩会检查 Apollo 客户端缓存以查看您请求的所有数据是否已在本地可用。如果所有数据都在本地可用,请使用查询 returns 该数据并且不查询您的 GraphQL 服务器。此 cache-first 策略是 Apollo Client 的默认获取策略。如果您说您将在突变后调用 handleRefresh(),则以下代码将正常工作。

here read fetch policy

  const { loading: loadingO, error: errorO, data: dataO, refetch: refetchO } = useQuery(GET_OWNER, {
  fetchPolicy: "network-only",
})
  const { loading: loadingM, error: errorM, data: dataM, refetch: refetchM } = useQuery(GET_MANAGER, {
  fetchPolicy: "network-only",
})

  const handleRefresh = () => {
    setRefresh(!refresh)
    if (role && id){
      if (role == "MANAGER"){
        refetchM()
      }
      if (role == "OWNER"){
        refetchO()
      }
    }
  }