如果你有 apollo react hooks 从后端获取数据,你如何使用 nextjs 进行服务器端渲染?

How do you do server side rendering with nextjs if you have apollo react hooks to fetch data from backend?

我有一个使用 apollo graphql 从后端获取数据的 nextjs 项目。我正在尝试使用服务器端渲染来渲染我的页面。但是我目前正在使用 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;

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,
    },
  };
};