使用 NextJS getServerSideProps 进行 Apollo 查询?

Apollo query within NextJS's getServerSideProps?

我正在将 NextJS 与 Apollo 一起使用。文档没有说太多,但指向这个 repo:https://github.com/vercel/next.js/tree/canary/examples/with-apollo

其中使用此代码:

export async function getStaticProps() {
  const apolloClient = initializeApollo()

  await apolloClient.query({
    query: ALL_POSTS_QUERY,
    variables: allPostsQueryVars,
  })

  return {
    props: {
      initialApolloState: apolloClient.cache.extract(),
    },
    unstable_revalidate: 1,
  }
}

我觉得那很丑所以我试着用钩子:

const res = useQuery(ALL_POSTS_QUERY);

但是我得到一个错误:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

那么在getStaticPropsgetServerSideProps里面可以不使用hooks吗?如果是这样,是否有更好的语法来进行 GraphQL 查询?

您可以使用 GraphQL 代码生成器使它变得更好。

例如,我正在做类似的事情,我的代码如下所示:

const response = await apolloClient.query<ViewerQuery>({
  query: ViewerDocument,
});

其中 ViewerQueryViewerDocument 由 GraphQL 代码生成器生成。