Evanss
Evanss

Reputation: 23593

Apollo query within NextJS's getServerSideProps?

I'm using NextJS with Apollo. The docs don't say much but point to this repo: https://github.com/vercel/next.js/tree/canary/examples/with-apollo

Which uses this code:

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

I find that quite ugly so I tried using a hook:

const res = useQuery(ALL_POSTS_QUERY);

But I get an error:

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:

So can you not use hooks inside getStaticProps and getServerSideProps? If so is there a nicer syntax for making GraphQL queries?

Upvotes: 5

Views: 4695

Answers (1)

arcticmatt
arcticmatt

Reputation: 2004

You can use GraphQL Code Generator to make this nicer.

For example, I'm doing something similar and my code looks like this:

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

where ViewerQuery and ViewerDocument are generated by GraphQL Code Generator.

Upvotes: 2

Related Questions