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

Time:04-02

I am relatively new to Apollo and GraphQL, and I need to make a requery after several mutations, since the recoil states don't want to update in time and a million errors get thrown off after some of the mutations. I simply put do not know how to do this and have been unable to find any relevant documentation to my scenario. The following code is inside of theApp.js file.

// 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])

...where handleRefresh is essentially called after every mutation, or of course, every refresh. However, just calling refetch does not work, and I have been very unable to find the proper syntax for my issue. Does anyone know the solution?

CodePudding user response:

By default, the useQuery hook checks the Apollo Client cache to see if all the data you requested is already available locally. If all data is available locally, useQuery returns that data and doesn't query your GraphQL server. This cache-first policy is Apollo Client's default fetch policy. If you say that you will call handleRefresh() after mutation the below code will work fine.

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()
      }
    }
  }

CodePudding user response:

Try this directly from apollo docs:

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."

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

  • Related