sitecore client – Fetch grapghQl response in next js

you have added endCursor, hasNext in your query. so, If you want to get all the data based on these two variables and in small chunks.

You can try this.

I already tried for my footer component, there so many navigation links. so, I called graphql query multiple times to get navigation links in small chucks.

I called in graphql query in getStaticProps, so it will get call the query multiple time in build time only. and i added query in diffent file ./Footer.graphql

import React from 'react';
import { FooterNavDocument } from './Footer.graphql';
import {
  GetStaticComponentProps,
  GraphQLRequestClient,
  constants,
} from '@sitecore-jss/sitecore-jss-nextjs';
import config from '@/temp/config';

const Footer = (_props: any): JSX.Element => {
  return <>Footer>;
};
export const getStaticProps: GetStaticComponentProps = async (rendering, layoutData) => {
  if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
    return null;
  }
  const graphQLClient = new GraphQLRequestClient(config.graphQLEndpoint, {
    apiKey: config.sitecoreApiKey,
  });
  const result = await graphQLClient
    .request(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      FooterNavDocument as any,
      {
        datasource: rendering.dataSource,
        contextItem: layoutData?.sitecore?.route?.itemId,
        language: layoutData?.sitecore?.context?.language,
        afterValue: '',
      }
    )
    .then(async (data: any) => {
      while (data.pageInfo.hasNext) {
        await graphQLClient
          .request(
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            FooterNavDocument as any,
            {
              datasource: rendering.dataSource,
              contextItem: layoutData?.sitecore?.route?.itemId,
              language: layoutData?.sitecore?.context?.language,
              afterValue: data.pageInfo.endCursor,
            }
          )
          .then(async (newdata: any) => {
            data.results.push(...newdata.results);
            data.pageInfo = newdata.pageInfo;
            return data;
          });
      }
      return data;
    });
  return result;
};
export default Footer;

so, here it will call graphql call till data.pageInfo.hasNext, and it will give data after data.pageInfo.endCursor value in every call.

Read more here: Source link