【问题标题】:How do you do server side rendering with nextjs if you have apollo react hooks to fetch data from backend?如果你有 apollo react 钩子从后端获取数据,你如何使用 nextjs 进行服务器端渲染?
【发布时间】:2021-07-20 14:32:06
【问题描述】:

我有一个 nextjs 项目,它使用 apollo graphql 从后端获取数据。我正在尝试使用服务器端渲染来渲染我的页面。但我目前正在使用 graphql apollo react hooks 从后端获取我的数据,react hooks 阻止我在 getServerSideProps 中调用我的后端。

我该如何解决这个问题?

import * as React from "react";
import { useExampleQuery } from "graphql/types";

export const getServerSideProps = async ({ params }) => {
  // Here we should probably call graphql function that is now called inside Page
  return { props: { hash: params.hash } };
};

const Page = ({ hash }) => {
  /* 
    I am currently calling my graphql query here using apollo react hooks, 
    that are generated inside graphql/types using @graphql-codegen (typescript)
  */
  const { data, loading } = useExampleQuery({
    variables: {
      hash: hash,
    },
  });

  return loading ? <p>{loading}</p> : <p>{data.example.text}</p>;
};

export default Page;

【问题讨论】:

    标签: typescript graphql react-hooks next.js server-side-rendering


    【解决方案1】:

    getServerSideProps 是一个服务器端函数,所以你不能完全调用它里面的 apollo 查询钩子。

    一种方法是使用apollo客户端实例查询方法。

    请参阅下面的示例代码。

    import { gql } from '@apollo/client';
    import apolloClient from '/path/to/graphql/server/client';
    
    // Example Query
    const EXAMPLE_QUERY = gql`
      query EXAMPLE_QUERY($hash: String!) {
        exampleQuery(hash: $hash) {
          ...
        }
      }
    `;
    
    export const getServerSideProps = async ({ params }) => {
      const { data } = await apolloClient.query({
        query: EXAMPLE_QUERY,
        variables: { hash: params.hash },
      });
    
      return {
        props: {
          hash: params.hash,
          data,
        },
      };
    };
    

    另外,如果导入你的 apollo 客户端服务器实例有点不清楚,你可以使用这个 graphql-request 包在给定 URL 的情况下发出 graphql 请求。

    查看示例

    import { GraphQLClient } from "graphql-request";
    
    // Replace GRAPHQL_URL below to actual
    const client =  new GraphQLClient(<GRAPHQL_URL>);
    
    export const getServerSideProps = async ({ params }) => {
    
      const { data } = await client.request(EXAMPLE_QUERY, {
          hash: params.hash 
      });
    
      return {
        props: {
          hash: params.hash,
          data,
        },
      };
    };
    

    【讨论】:

    • 谢谢,真的很有帮助!因此,正如您所说,我正在尝试创建一个新的 graphql 客户端,但我收到“网络错误:对localhost:3001/graphql 的请求失败,原因:连接 ECONNREFUSED 127.0.0.1:3001”。你知道问题可能是什么吗?我可以访问其他网址。在我的 initApollo 文件中初始化 apollo 客户端时,我没有收到该错误,但我无法从我的 initApollo 内部访问客户端
    • 导出在您的initApollo 文件中工作的客户端并在此处使用该实例。但是,我可以看看你是如何创建一个新的 graphql 客户端的吗? @Atonic
    猜你喜欢
    • 2019-10-02
    • 2017-09-19
    • 2019-10-05
    • 2020-01-21
    • 2017-12-02
    • 2018-05-22
    • 2020-11-06
    • 2016-08-06
    • 2017-08-13
    相关资源
    最近更新 更多