在react-apollo中使用refetchQueries时使用现有变量

Kum*_*rup 7 javascript apollo graphql react-apollo prisma-graphql

我正在使用postsConnection无限滚动查询。它包含诸如 之类的变量after。进行赞成突变后,我想refetchQueries......像这样

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

上面的代码给出错误,因为POST_AUTHOR_QUERY接受很少的变量。这是该查询

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

我不想手动添加变量。变量已经存储在缓存中。使用时如何重复使用它们refetchQueries???

以下是我读过的有关此问题的一些资源

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

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

Dan*_*den 5

正如您链接的问题中提到的,您应该能够执行以下操作:

import { getOperationName } from 'apollo-link'

const upvote = await client.mutate({
  // other options
  refetchQueries={[getOperationName(POST_AUTHOR_QUERY)]}
})
Run Code Online (Sandbox Code Playgroud)

来自文档

请注意,如果您使用字符串数组调用 refetchQueries,那么 Apollo 客户端将查找与提供的字符串同名的任何先前调用的查询。然后它将使用当前变量重新获取这些查询。

getOperationName只需解析您传递给它的文档并从中提取操作名称。当然,您可以自己将操作名称作为字符串提供,但这种方式可以避免操作名称将来发生更改或您误操作时出现的问题。


Mar*_*o K 5

如果您不想拉入apollo-link,您也可以通过基础graphql包获取它(请注意,为了方便起见,我使用可选链接:

import { getOperationAST } from 'graphql';


const operationName = getOperationAST(POST_AUTHOR_QUERY)?.name?.value;
// Note that this could technically return `undefined`

const upvote = await client.mutate({
  mutation: UPVOTE_MUTATION,
  variables: {
    postId: this.props.post.id
  },
  refetchQueries: [operationName]
})
Run Code Online (Sandbox Code Playgroud)