'WpGraphQL query returns null

I'm having this GraphQL query from headless Wordpress in Nexjs via WpGraphQl plugin:

export const GET_POSTS_BY_CATEGORY_SLUG = gql`
 query GET_POSTS_BY_CATEGORY_SLUG( $slug: String, $uri: String, $perPage: Int, $offset: Int ) {
 ${HeaderFooter}
  page: pageBy(uri: $uri) {
    id
    title
    content
    slug
    uri
    seo {
      ...SeoFragment
    }
  }
  categories(where: {slug: $slug}) {
    edges {
      node {
        slug  
        posts: posts(where: { offsetPagination: { size: $perPage, offset: $offset }}) {
          edges {
            node {
              id
              title
              excerpt
              slug
              featuredImage {
                node {
                  ...ImageFragment
                }
              }
            }
          }
          pageInfo {
            offsetPagination {
              total
            }
          }
        }
      }
    }
  }
}
 ${MenuFragment}
 ${ImageFragment}
 ${SeoFragment}
 `;

And this is my getStaticProps function:

export async function getStaticProps(context) {
  

  const { data: category_IDD } = await client.query({
    query: GET_POSTS_BY_CATEGORY_SLUG,
  });
  

  const defaultProps = {
    props: {
      
      cat_test: JSON.parse(JSON.stringify([category_IDD])),
    },

    revalidate: 1,
  };

  return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}

If i pass it like this in props:

const defaultProps = {
    props: {

      cat_test: category_IDD,
    },

i get an error saying:

SerializableError: Error serializing `.cat_test` returned from `getStaticProps` in "/category/[slug]". Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.

But when i JSON.parse as the code above, i get null

Whats wrong with this query?



Solution 1:[1]

Just noticed that the $slug is an array of strings, so here should be:

query GET_POSTS_BY_CATEGORY_SLUG( $slug: [String], $uri: String, $perPage: Int, $offset: Int )

instead of $slug: String

Solution 2:[2]

You're not actually passing the $slug variable to the query. For instance if your page route is /category/[slug].js your getStaticProps should look something like this.

export async function getStaticProps(context) {
  const { slug } = context.params;

  const { data: category_IDD } = await client.query({
    query: GET_POSTS_BY_CATEGORY_SLUG,
    variables: { slug },
  });
  

  const defaultProps = {
    props: {
      
      cat_test: JSON.parse(JSON.stringify([category_IDD])),
    },

    revalidate: 1,
  };

  return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Geoff Taylor