如何在next.js getServerSideProps()中从包装器获取客户端?

时间:2020-11-04 14:23:28

标签: reactjs graphql next.js apollo server-side-rendering

我试图将next.js与apollo graphql一起用于服务器端渲染。我知道,要做到这一点,我需要在getServerSideProps()中运行必要的查询,然后将其传递到主要组件中,从而可以呈现结果。

我创建了一个提供程序,以确保树中的所有组件都获得相同的客户端对象。

import withApollo from "next-with-apollo";
import { ApolloClient, InMemoryCache } from "@apollo/client";
import { ApolloProvider } from "@apollo/react-hooks";

export default withApollo(
  () => {
    return new ApolloClient({
      ssrMode: true,
      uri: "https://my.api/graphql",

      cache: new InMemoryCache()
    });
  },
  {
    render: ({ Page, props }) => {
      return (
        <ApolloProvider client={props.apollo}>
          <Page {...props} />
        </ApolloProvider>
      );
    }
  }
);

但是如果不由withApollo()包装,该如何在getServerSideProps()函数中获取此客户端?

import gql from "graphql-tag";
import { useQuery } from "@apollo/react-hooks";
import { ApolloClient } from "@apollo/client";
import withApollo from "next-with-apollo";

const MY_QUERY = gql`
  query MyQuery {
    myQuery {
      name
    }
  }
`;

function MyComponent(props) {
  return (
    <div className="landing-section__topcontainer ph-lg-8 ph-3">
      <div className="overflow-list-container">
        <div className="landing-horizontal-list">
          {props.res.map(q => {
            return (
               <div className="tag-tile__title">{q.name}</div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

export async function getServerSideProps() {
  // Fetch data from external API

  const apolloClient = getApolloClient();

  const { data } = await apolloClient.query({
    query: MY_QUERY
  });
  const res = data.myQuery;

  return { props: { res } };
}

export default withApollo(MyComponent);

0 个答案:

没有答案