【问题标题】:query works with useQuery hook but not with ApolloClient instance查询适用于 useQuery 挂钩,但不适用于 ApolloClient 实例
【发布时间】:2020-06-17 08:33:50
【问题描述】:

我遇到了一个问题,使用 useQuery Apollo 挂钩运行查询工作正常,但如果我使用 useApolloClient 挂钩获取 ApolloClient 的实例,然后调用客户端的 query 方法,调用失败,错误为Error: query option is required. You must specify your GraphQL document in the query option.

我的代码或多或少是这样的:

import React from 'react'
import gql from 'graphql-tag'
import { useQuery, useApolloClient } from '@apollo/react-hooks'

const MyComponent = props => {

  const QUERY = gql`
    query MyPersonSearch ( $after: String, $filter: PersonFilter, $first: Int ) {
      people: people ( after: $after, filter: $filter, first: $first ) {
        totalCount
        pageInfo {
          endCursor
          hasNextPage
        }
        edges {
          node {
            firstName
            lastName
          }
        }
      }
    }
  `

  const queryVars = cursor => { after: cursor, ...otherQueryVars }

  // This works
  const { loading, error, data, fetchMore } = useQuery(
    QUERY, { variables: queryVars( ... ) }
  )

  // This doesn't work
  const client = useApolloClient()
  const fetchPages = async () => {
    const { data } = await client.query( QUERY, { variables: queryVars( ... ) } )
  }


  ...
} 

知道这里发生了什么吗?错误消息有点含糊,但我假设这意味着 client.query() 需要 DocumentNode 作为它的第一个参数,gql 的返回类型是 any...是真的,我希望useQuery 也会失败,因为它还希望查询是DocumentNode

【问题讨论】:

    标签: apollo react-apollo apollo-client


    【解决方案1】:

    Welp,原来语法不一样。 client.query() 需要一个唯一的 QueryOptions 参数,而 useQuery 可以将查询作为第一个参数,以及可选的 QueryOptions 第二个参数。

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 2011-05-20
      • 2020-04-13
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多