具有Apollo身份验证的Nexjs,无法读取未定义的属性“查询”

时间:2018-12-21 02:57:26

标签: graphql react-apollo next.js

我一直在从Nextjs repo来指导这个示例,并将其实现到我的项目中,但会抛出此错误:

enter image description here

我的API不适用于json网络令牌,但我已经使用cookie正确定义了ApolloProvider ...您可以在此处查看完整的代码:

屏幕截图的组件来自pages / login.js。

https://github.com/MontoyaAndres/BarHalem

并使用docker-compose -f docker-compose.dev.yml up --build

测试它在服务器文件夹yarn dev和客户端文件夹中运行的情况

1 个答案:

答案 0 :(得分:0)

仅将ctx.ctx.apolloClient = apollo添加到withApollo.js文件中,所有方法都可以使用。完整的代码为:

import React from "react";
import Head from "next/head";
import { getDataFromTree } from "react-apollo";

import initApollo from "./initApollo";

export default App => {
  return class WithData extends React.Component {
    static displayName = `WithData(${App.displayName})`;

    static async getInitialProps(ctx) {
      const { Component, router } = ctx;
      const apollo = initApollo({});

      ctx.ctx.apolloClient = apollo;

      let appProps = {};
      if (App.getInitialProps) {
        appProps = await App.getInitialProps(ctx);
      }

      // Run all GraphQL queries in the component tree
      // and extract the resulting data
      if (!process.browser) {
        try {
          // Run all GraphQL queries
          await getDataFromTree(
            <App
              {...appProps}
              Component={Component}
              router={router}
              apolloClient={apollo}
            />
          );
        } catch (error) {
          console.error("Error while running `getDataFromTree`", error);
        }

        // getDataFromTree does not call componentWillUnmount
        // head side effect therefore need to be cleared manually
        Head.rewind();
      }

      // Extract query data from the Apollo store
      const apolloState = apollo.cache.extract();

      return {
        ...appProps,
        apolloState
      };
    }

    constructor(props) {
      super(props);
      this.apolloClient = initApollo(props.apolloState);
    }

    render() {
      return <App {...this.props} apolloClient={this.apolloClient} />;
    }
  };
};