Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use existing variables when using refetchQueries in react-apollo

I am using postsConnection query for infinite scroll. It contains variables like after. After doing an upvote mutation, I want to refetchQueries... like this 👇

const upvote = await client.mutate({
      mutation: UPVOTE_MUTATION,
      variables: {
        postId: this.props.post.id
      },
      refetchQueries: [
        { query: POST_AUTHOR_QUERY }
      ]
    })

Above code gives error because POST_AUTHOR_QUERY accepts few variables. Here's that query 👇

export const POST_AUTHOR_QUERY = gql`
    query POST_AUTHOR_QUERY($authorUsername: String! $orderBy: PostOrderByInput $after: String){
        postsAuthorConnection(authorUsername: $authorUsername orderBy: $orderBy after: $after) {
                   ....
        }
    }

I do not want to add variables manually. Variables are already stored in the cache. How do I reuse them while using refetchQueries???

Here are a few resources I have read about this issue 👇

https://github.com/apollographql/react-apollo/issues/817

https://github.com/apollographql/apollo-client/issues/1900

like image 243
Kumar Abhirup Avatar asked Mar 04 '23 04:03

Kumar Abhirup


1 Answers

As mentioned in the issue you linked, you should be able to do the following:

import { getOperationName } from 'apollo-link'

const upvote = await client.mutate({
  // other options
  refetchQueries={[getOperationName(POST_AUTHOR_QUERY)]}
})

From the docs:

Please note that if you call refetchQueries with an array of strings, then Apollo Client will look for any previously called queries that have the same names as the provided strings. It will then refetch those queries with their current variables.

getOperationName simply parses the document you pass it and extracts the operation name from it. You can, of course, provide the operation name yourself as a string instead, but this way avoids issues if the operation name changes in the future or you fat finger it.

like image 197
Daniel Rearden Avatar answered Mar 06 '23 17:03

Daniel Rearden