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

Ato*_*nic 3 typescript graphql server-side-rendering next.js react-hooks

我有一个 nextjs 项目,它使用 apollo graphql 从后端获取数据。我正在尝试使用服务器端渲染来渲染我的页面。但我目前正在使用 graphql apollo 反应钩子从后端获取数据,并且反应钩子阻止我在 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;
Run Code Online (Sandbox Code Playgroud)

for*_*nee 8

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

另外,如果导入 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,
    },
  };
};
Run Code Online (Sandbox Code Playgroud)