GraphQL with Next.js 13 Server Components

31 Oct 2022

const GetAllPostsDocument = graphql(/* GraphQL */ `
  query GetAllPosts($first: Int!) {
    postCollection(first: $first) {
      edges {
        node {
          id
          title
          slug
        }
      }
    }
  }
`);

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { postCollection } = await graphqlClient.request(GetAllPostsDocument, {
    first: 10,
  });

  return (
    <html>
      <head></head>
      <body>
        <nav>
          <ul>
            {postCollection?.edges?.map((edge) =>
              edge?.node ? (
                <li key={edge.node.id}>
                  <Link href={`/posts/${edge.node.slug}`}>
                    {edge.node.title}
                  </Link>
                </li>
              ) : null
            )}
          </ul>
        </nav>
        <main>{children}</main>
      </body>
    </html>
  );
}
export const revalidate = 3600;

const GetPostBySlugDocument = graphql(/* GraphQL */ `
  query GetPostBySlug($slug: String!) {
    post(by: { slug: $slug }) {
      id
      title
      slug
    }
  }
`);

const Page = async ({ params }: { params: { slug: string } }) => {
  const { post } = await graphqlClient.request(GetPostBySlugDocument, {
    slug: params.slug,
  });

  if (!post) {
    return <h1>404</h1>;
  }

  return <pre>{JSON.stringify(post, null, 2)}</pre>;
};

export default Page;