Fetch component-level data in Next.js app using GraphQL - Sitecore Headless Development

When we develop headless application in Next Js, we need to fetch the data from Sitecore for our components.

Mostly, we do this by implementing and exporting getStaticProps for static generation (SG), or getServerSideProps for server-side rendering (SSR).

The SitecorePagePropsFactory class uses an instance of the ComponentPropsService class that helps to identify which components require retrieval of data. The ComponentPropsService is provided by the NPM package @sitecore-jss/sitecore-jss-nextjs. For more details please refer this link.

Use GraphQL to fetch component-level data in JSS Next.js apps

GraphQL queries are very helpful when we need to fetch specific content for the components. It provides the flexibility to combine multiple data sources in a single query, and receive the requested data in a single response. 

Let's try to implement one use case of this where we'll fetch the State List for our Next.js component from Sitecore using GraphQL query. 

These are the steps which need to follow while fetching component-level data using GraphQL

  • Create one folder for GraphQL files in src folder. 
  • In GraphQL folder create one file. Let's say - graphQLClient.ts
  • Copy-paste the following code in your graphQLClient.ts file.

import { GraphQLRequestClient } from '@sitecore-jss/sitecore-jss-nextjs';
import config from 'temp/config';

const graphQLClient = new GraphQLRequestClient(config.graphQLEndpoint, {
  apiKey: config.sitecoreApiKey,
});

export default graphQLClient;
Note - temp/config import in above code snippet is the build time auto generated configurations file which consist of all your defined configurations. For example these are the configurations expected in temp/config file.
const config = {};
config.sitecoreApiKey = process.env.SITECORE_API_KEY || "no-api-key-set",
config.sitecoreApiHost = process.env.SITECORE_API_HOST || "",
config.sitecoreCmUrl = process.env.SITECORE_CM_URL || "",
config.jssAppName = process.env.JSS_APP_NAME,
config.graphQLEndpointPath = process.env.GRAPH_QL_ENDPOINT_PATH || "/sitecore/api/graph/edge",
config.defaultLanguage = process.env.DEFAULT_LANGUAGE || "en",
config.graphQLEndpoint = process.env.GRAPH_QL_ENDPOINT || `${config.sitecoreApiHost}${config.graphQLEndpointPath}`;
module.exports = config;
  • Now create one more folder under GraphQL folder where all your queries files will be available. It should be something similar to this structure.
 
  • Now create one query file in queries folder. Let's name it stateList.query.ts for this example.
  • Write this GraphQL query to fetch State List based on the country code. This query might be different as per your requirement. 
  • The rootItemId and templates GUID parameters should be replaced with IDs. The rootItemId is your root folder Id where the State List is stored and templates ID is the ID of the State Item template.

import gql from 'graphql-tag';

const StateListQuery = gql`
  query StateListGLQuery($rootItemId: String!, $countryCode: String!, $templates: String!) {
    search(
      where: {
        AND: [
          { name: "_path", value: $rootItemId, operator: CONTAINS }
          { name: "_templates", value: $templates, operator: CONTAINS }
          { name: "countryCode", value: $countryCode, operator: EQ }
        ]
      }
    ) {
      results {
        language {
          name
        }
        children {
          stateList: results {
            stateName: name
            key: field(name: "key") {
              value
            }
            displayText: field(name: "value") {
              value
            }
          }
        }
      }
    }
  }
`;

export const getStateListQueryParameters = (countryCode: string) => ({
  //TODO: rootItemId and template should be read from sitecore context data
  rootItemId: '{25A60222-F59C-4FC1-8256-F1ED4B05D7F3}',
  countryCode,
  templates: '{35AEC51F-2CDC-4A8A-86FF-48640ECDDACA}',
});

export default StateListQuery;
  • We're almost done. Now we need to call this function in our component and we are done.
  • Open your component where you want to fetch the Stale List result. 
  • Add these lines in your component to get the result.
import graphQLClient from 'src/GraphQL/graphQLClient';
import StateListQuery,{getStateListQueryParameters} from 'src/GraphQL/queries/stateList.query';

const stateList = await graphQLClient.request<any>(
    StateListQuery as any,
    getStateListQueryParameters(countryCode)
);
That's it. Now, it should fetch the stateList from your configured Layout Service end point.

Comments

Popular posts from this blog

Setup Sitecore XM Cloud Dev Environment using Docker

Sitecore Content Hub - Triggers, Actions and Scripts

All Blog Posts - 2023