首页 > 解决方案 > ApolloProvider useQuery 组合不从 AWS AppSync 获取数据,在 React 项目中

问题描述

情况

由于兼容问题,我使用 ApolloClient 来形成我的 AWS AppSync API 客户端,以便我可以使用 ApolloProvider 将客户端传递给不同的子组件。

在子组件中,我调用 useQuery 来获取数据,但问题是输出总是给我默认的“未定义”值。

顶级代码

import awsconfig from '../aws-exports';
import { AUTH_TYPE } from 'aws-appsync';
import {
  ApolloProvider,
  ApolloClient,
  ApolloLink,
  HttpLink,
  InMemoryCache,
} from "@apollo/client";
import { createAuthLink } from "aws-appsync-auth-link";
import { getUserDb, listUserDbs } from '../graphql/queries';

const link = ApolloLink.from([
  createAuthLink({
    url: awsconfig.aws_appsync_graphqlEndpoint,
    region: awsconfig.aws_appsync_region,
    auth: {
      type: AUTH_TYPE.API_KEY,
      apiKey: awsconfig.aws_appsync_apiKey,
    },
  }),
  new HttpLink({ uri: awsconfig.aws_appsync_graphqlEndpoint }),
]);

const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
  credentials: 'include'
});

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

export default WithProvider;

子组件中的代码(useQuery的使用)

import { listUserDbs } from '../graphql/queries';
const GET_USER_PROFILE = gql(listUserDbs)

function App() {
  const { loading, error, out_data, client } = useQuery(GET_USER_PROFILE);
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

我做了什么测试?

  1. 当我直接从客户端调用查询时,它起作用了
client
  .query({
    query: gql`
      query ListUserDbs(
        $filter: Table
      ) {
        listUserDBS(filter: $filter) {
          items {
            sub
          }
          nextToken
        }
      }
    `
  })
  .then(result => console.log(result));
  1. 当我要求 useQuery 返回客户端时,它返回我设置的相同客户端
const { loading, error, out_data, client } = useQuery(LIST_USER_PROFILE);

我对这个问题的猜测

问题可能来自 useQuery 但我不知道如何解决它。

标签: javascriptreactjsamazon-web-servicesappsync-apollo-client

解决方案


也许你需要data而不是out_data?


推荐阅读