Search code examples
wordpressgraphqlnext.jsheadless-cms

Make GraphQL query nullable


I'm having a GraphQL Query to display posts from Wordpress Headless but i have some posts which don't have a featuredImage, and because of that i get TypeError: Cannot read property 'node' of null.

How do i make my query accept nullable elements hence displaying the page even though theres no featuredImage provided?

Here's my query:

import Image from "next/image";

export default function Post(data) {
  const post = data.post;
  return (
    <div>
      <h1>{post.title}</h1>
      <Image width="640" height="426" src={post.featuredImage.node.sourceUrl} />
      <article dangerouslySetInnerHTML={{ __html: post.content }}></article>
    </div>
  );
}

export async function getStaticProps(context) {
  const res = await fetch("https://www.torontowebmarketing.ca/graphql", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      query: `
        query SinglePost($id: ID!, $idType: PostIdType!) {
          post(id: $id, idType: $idType) {
              title
              slug
              content
              featuredImage{
                node {
                    sourceUrl
                }
               }
          }
        }
    
      `,
      variables: {
        id: context.params.slug,
        idType: "SLUG",
      },
    }),
  });
  const json = await res.json();

  return {
    props: {
      post: json.data.post,
    },
  };
}

Solution

  • Not a query/type problem, it's fine/legal (explore types in playground docs) to have null values for some props in dataset/tree.

    Just prepare your rendering function to handle nulls, lack of some values. You can do this using conditional rendering, in this case:

    {post.featuredImag && <Image....>}