skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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


  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");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search