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

dan*_*nca 8 reactjs graphql react-apollo aws-appsync aws-amplify

我是 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);

Run Code Online (Sandbox Code Playgroud)

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

类型错误:this.currentObservable.query.getCurrentResult 不是函数

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

钩子调用:

const {loading, error, data, refetch} = useQuery(gql(queries.listVideos));
Run Code Online (Sandbox Code Playgroud)

引发问题的被调用函数:

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,
Run Code Online (Sandbox Code Playgroud)

如果我使用该<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",
Run Code Online (Sandbox Code Playgroud)

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

Nah*_*ron 9

如果添加:

"resolutions": {
  "apollo-client": "2.6.3"
}
Run Code Online (Sandbox Code Playgroud)

在您package.json并重新安装它应该可以工作。

您可能会看到此警告:

Resolution field "apollo-client@2.6.3" is incompatible with requested version "apollo-client@2.4.6"
Run Code Online (Sandbox Code Playgroud)

这是因为 Appsync 依赖于旧版本的 react-apollo,但我发现它运行良好。

你可以关注这个问题,希望很快就能解决,我们不再需要这样做了。


Gui*_*sta 5

正如其他答案中提到的,问题是因为aws-appsync依赖于以前的版本apollo-client。使用分辨率不是解决此问题的“更干净”的方法,因为您正在修复与此库不完全兼容的依赖项版本。

我强烈建议您通过以下方式为 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
Run Code Online (Sandbox Code Playgroud)

我还在媒体上创建了一个更详细的帖子