AWS AppSync + React-Apollo Query/useQuery 引发异常 this.currentObservable.query.getCurrentResult 不是函数

AWS AppSync + React-Apollo Query/useQuery raising exception this.currentObservable.query.getCurrentResult is not a function

我是 GraphQL/Apollo 的新手,我很难用 React 应用程序设置它。

我有一个 React 组件,它从使用 Amplify/AppSync 构建的 GraphQL API 加载列表。

如果我手动调用来获取项目,即:

    const videosData = await client.query({
      query: gql(queries.listVideos)
    });
    const videosItems = videosData.data.listVideos.items;
    setVideosData(videosItems);

很有魅力。 但是,如果我尝试使用 Apollo Query 组件或 useQuery 挂钩,则会引发以下错误:

TypeError: this.currentObservable.query.getCurrentResult is not a function

如果我只是添加行以使用挂钩获取查询,它已经给我这个错误

钩子调用:

const {loading, error, data, refetch} = useQuery(gql(queries.listVideos));

引发问题的调用函数:

QueryData.getQueryResult
node_modules/@apollo/react-hooks/lib/react-hooks.esm.js:325
  322 |     called: true
  323 |   });
  324 | } else {
> 325 |   var currentResult = this.currentObservable.query.getCurrentResult();
      | ^  326 |   var loading = currentResult.loading,
  327 |       partial = currentResult.partial,
  328 |       networkStatus = currentResult.networkStatus,

如果我使用 <Query> 组件

,则会发生完全相同的问题

包版本:

"aws-amplify": "^1.1.30",
"aws-amplify-react": "^2.3.10",
"aws-appsync": "^1.8.1",
"graphql-tag": "^2.10.1",
"react-apollo": "^3.0.1",

知道我可能做错了什么以及如何解决吗?

如果您添加:

"resolutions": {
  "apollo-client": "2.6.3"
}

在您的 package.json 中重新安装应该可以。

您可能会看到此警告:

Resolution field "apollo-client@2.6.3" is incompatible with requested version "apollo-client@2.4.6"

这是因为 Appsync 依赖于旧版本的 react-apollo,但我发现它工作正常。

您可以关注 this issue,希望很快就能解决,我们不再需要这样做了。

如其他答案所述,问题是因为 aws-appsync 依赖于以前的版本 apollo-client。 使用分辨率不是解决此问题的 "cleaner" 方法,因为您正在修复与该库不完全兼容的依赖版本。

我强烈建议您以这种方式为 AWS AppSync 创建自定义 apollo 客户端:

import { ApolloProvider } from '@apollo/react-hooks';
import { ApolloLink } from 'apollo-link';
import { createAuthLink } from 'aws-appsync-auth-link';
import { createHttpLink } from 'apollo-link-http';
import { AppSyncConfig } from '.aws-exports';
import ApolloClient from 'apollo-client';
import { InMemoryCache } from "apollo-cache-inmemory";

const url = AppSyncConfig.graphqlEndpoint;
const region = AppSyncConfig.region;
const auth = {
  type: AppSyncConfig.authenticationType,
  apiKey: AppSyncConfig.apiKey
};
const link = ApolloLink.from([
   createAuthLink({ url, region, auth }), 
   createHttpLink({ uri: url })
]);
const client = new ApolloClient({
  link,
  cache: new InMemoryCache()
});

const WithProvider = () => (
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
)

export default WithProvider

我还在 medium

上创建了一个更详细的 post