The query to WpGraphQL results in a null response

I am currently working with a GraphQL query in Nexjs that is connected to headless Wordpress via the 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}
 `;

This is how my getStaticProps function looks like:

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");
}

When I try passing it in props like this:

const defaultProps = {
    props: {

      cat_test: category_IDD,
    },

An error occurs stating:

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.

However, if I apply JSON.parse as shown in the code above, I get null

What could be causing this issue with the query?

Answer №1

It recently came to my attention that the variable $slug is actually an array of strings, so the correct syntax should be:

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

instead of $slug: String

Answer №2

Make sure to pass the $slug variable correctly in your query function. For example, if your page route is /category/[slug].js, your getStaticProps method should be structured like this:

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

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

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

    revalidate: 1,
  };

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for accessing various font weights in NextJS?

I'm stuck trying to figure out what I'm messing up. I have this code in mind: <link href="https://fonts.googleapis.com/css2family=Montserrat:wght@300;400;200&display=swap" rel="preload" as="font" crossOrigin=& ...

When working with the "agora-rtc-sdk-ng" package, an error may be thrown by Next.js stating that "window is not defined"

Currently, I am in the process of incorporating the "agora-rtc-sdk-ng" package for live streaming with next.js and typescript. import AgoraRTC from 'agora-rtc-sdk-ng'; However, when I try to import it, an error is thrown as shown below: https:/ ...

What is the best way to access the next-auth session using getStaticPaths and getStaticProps in dynamic routing scenarios?

I am currently working on implementing dynamic routing in a NextJS application. I need to retrieve the token from next-auth in order to make axios requests to an API and fetch data from getReport and getReports (located in /reports.js). However, I am facin ...

Struggling with mapping through a multidimensional array?

I'm facing an issue with using .map() on a nested array. I initially tried to iterate through my stored data using .map(), and then attempted another iteration within the first one to handle the nested array, but it didn't work as expected. The ...

What are the steps to seamlessly embed Rocket.chat Omnichannel livechat into an iframe without the open/close button?

I am looking to add a live chat feature in an iframe on my website without the open/close button, only utilizing the onichannel chat layout. I attempted something like the following: 'use client'; import React from 'react'; export con ...

When trying to pass props from a parent to a component in Next.js, the issue of props

Within /pages/profile.js, I am utilizing the LovedOne element by passing values from props. Upon debugging, it is evident that these values are indeed valid when passed. import React from "react"; import LovedOne from "../components/loved_on ...

Establishing a Recyclable Testing Rendering Method in redux toolkit version 2

In the era of Redux Toolkit v2, a noticeable change occurred with the absence of the EmptyObject type and the unavailability of the PreloadedState type in the @reduxjs/toolkit package. This has led to a requirement of defining all reducers inside the pre ...

Tips for integrating Bootstrap 4.5 variables into NextJS seamlessly

I have a new concept in mind - integrating Bootstrap 4.5 into NextJS and customizing variables as demonstrated here: The structure of my files is within the pages folder: _app.js import '../styles/main.scss' function MyApp({ Component, pageProp ...

Exploring opportunities to earn revenue from a website created with Next Js through Adsterra

I've been exploring options to monetize my Next Js website using Adsterra. However, I encountered an issue when trying to implement the Google Adsense code specifically designed for Next js. Should the code be placed within _document.js? <scrip ...

Encountering a snag while attempting to launch NextJS application on Vercel platform

I've been facing an issue while attempting to deploy my NextJS application on Vercel. The error message I keep encountering is as follows: 19:07:34.256 > Build error occurred 19:07:34.257 Error: Failed to load config "next/babel" to exten ...

What is the best way to retrieve the precise query string in a Next.js 14 application router when running on the server?

Is there a way to retrieve the precise query string on the server when utilizing app router? While I am aware of using the searchParams property to obtain the object version of search parameters, I am curious about accessing the exact query string compar ...

Next.js does not support Video.js functionality when using server side rendering

I'm struggling to set up video.js in my next.js project and encountering issues. When the player is loading, it initially appears black and then disappears abruptly. A warning message in the console reads: "video.es.js?31bb:228 VIDEOJS: WARN: T ...

Client-side image upload problem in Next.js API routes

I've been banging my head against this bug for a couple of hours now and I just can't seem to figure out the reason behind it. The issue is with an API route I'm trying to set up in next.js where I need to modify an image and then upload it ...

Important notice: It is not possible to assign refs to function components. Any attempt to do so will result in failure. If you intended to assign a ref, consider

My console is showing a warning when I use the nextJs Link component. Can someone assist me in resolving this issue and providing an explanation? Here is the message from the console: https://i.stack.imgur.com/jY4FA.png Below is a snippet of my code: im ...

What is the best way to set up deployment tracking for Next.js without using a custom server?

In the midst of developing a project using Next.js, we have opted to run it WITHOUT the custom server, instead relying on next build + next start. For our backend, whenever a new version is deployed and goes live, we notify the team through a log service. ...

Conceal the Root layout from Next.js 14 on a separate page

I am currently utilizing the app router within my Next.js 14 project. The folder structure of my project is as follows: -- dashboard/ /page.tsx # using main layout /layout.tsx --create /page. ...

The files _buildmanifest.js and _ssgmanifest.js could not be loaded. The server returned a 404 error, indicating that the resources were not found

Upcoming: 12.3.4 React Version: 17.0.2 Node Version: 16.13.1 An error is persisting in my Next.js application where the console displays the following message on all pages I load: 404 Failed to load resource: the server responded with a status of 404 ( ...

Oops! Error: EPERM - operation forbidden

When attempting to execute the yarn build command, I encountered this error message. An error occurred during the build process [Error: EPERM: operation not permitted, open 'C:\Program Files (x86)\cmder\podcastr\.next\routes-m ...

Incorporating real-time camera scanning using "react-qr-reader" in your React application

Hello, I've been working on creating a web-based QR scanner using Next.js, but I'm struggling to figure out how to implement live video for scanning QR codes. import React, { Component } from "react"; import dynamic from "next/dyna ...

Encountering an issue during the initialization of a NextJS app due to an ENO

When attempting to create a Next.js App using npx create-next-app@latest, the build fails after about 10 seconds, and I encounter the following error: npm ERR! Windows_NT 10.0.19045 npm ERR! argv "C:\\Program Files\\nodejs\&bs ...