【问题标题】:Use existing variables when using refetchQueries in react-apollo在 react-apollo 中使用 refetchQueries 时使用现有变量
【发布时间】:2019-09-02 11:18:49
【问题描述】:

我正在使用postsConnection 查询无限滚动。它包含像after 这样的变量。 在进行了upvote 突变后,我想refetchQueries... 像这样????

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

上面的代码给出了错误,因为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) {
                   ....
        }
    }

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

这里有一些我读过的关于这个问题的资源????

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

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

【问题讨论】:

    标签: javascript graphql apollo react-apollo prisma-graphql


    【解决方案1】:

    the issue you linked 中所述,您应该能够执行以下操作:

    import { getOperationName } from 'apollo-link'
    
    const upvote = await client.mutate({
      // other options
      refetchQueries={[getOperationName(POST_AUTHOR_QUERY)]}
    })
    

    来自docs

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

    getOperationName 只是解析您传递给它的文档并从中提取操作名称。当然,您可以自己提供操作名称作为字符串,但这样可以避免将来操作名称更改或您粗心大意时出现问题。

    【讨论】:

    • 根据需要填充一个变量authorUsername。但是after 变量似乎是空白的。
    【解决方案2】:

    如果你不想拉入apollo-link,你也可以通过基本的graphql 包来获得这个(注意,为了方便,我使用optional chaining

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

    【讨论】:

      猜你喜欢
      • 2018-10-09
      • 2019-10-17
      • 2019-02-17
      • 2019-10-14
      • 2018-09-25
      • 2021-10-04
      • 2018-11-19
      • 2020-06-21
      • 2019-06-20
      相关资源
      最近更新 更多