How to update query in apollo client?

Viewed 4550

Let's say I have a simple data model like this

User
 - email
 - password
 - Profile
    - profile_image
    - address
    - phone_number

When I visit the user's profile page, I use useQuery and query user from server

const ME = gql`
  query {
    me {
      email
      profile {
        profileImage
        address
        phoneNumber
      }
  }
`; 
const {loading, data, refetch} = useQuery(ME);

And when I want to update a profile. I will do this

const UPDATE_PROFILE = gql`
  mutation($profileImage: String!, $address: String!, $phoneNumber: String!) {
    updateProfile(profileImage: $profileImage, address: $address, phoneNumber: $phoneNumber) {
      profileImage
      address
      phoneNumber
    }
  }
`;

const [updateProfile, {loading}] = useMutation(UPDATE_PROFILE, {
  onCompleted(data) {
    // Refetch to refresh whole user data
    refetch();
  }
}

I just want to display new updated user info in the page, So What I do is calling refetch() from useQuery(ME).

But I found that I can use refetchQueries() from this doc. Which will be a better choice? What is the difference between them?

1 Answers

The difference between refetchQueries and refetch:

  • refetchQueries: you can refetch any queries after a mutation including your ME query or other queries like getMessageList, getListUser,...

    refetchQueries is the simplest way of updating the cache. With refetchQueries you can specify one or more queries that you want to run after a mutation is completed in order to refetch the parts of the store that may have been affected by the mutation (refetchQueries doc).

  • refetch: you just can refetch query ME when your use refetch which is one of the results of useQuery(ME).

    A function that allows you to refetch the query and optionally pass in new variables (refetch doc).

In your case, if you want to refetch your ME data, you can use refetch. On the other hand, if your want to update other queries you should use refetchQueries.
In my experience, I prefer using refetchQueries after a mutation to using refetch.

Related