GraphQL query to fetch the country specific state list - Sitecore Headless Development

Application Architecture: We have a multilingual site which is developed based on Sitecore headless architecture using Next Js as front end application. We are using Sitecore 10.3 with Experience Edge service. The Sitecore solution is deployed on Sitecore XM managed cloud and the front end Next JS application deployed on Vercel cloud platform.

Use Case: We need to pre-populate the State dropdown for the selected country. The country is auto selected based on the Sitecore IP Geolocation Service call at the time of Site rendering.

Solution: We're going to use the GraphQL query to fetch the country specific state list. We'll make this GraphgQL call from Next JS  application at the time of component rendering. 

Following query parameters will be passed to get the country specific state list.

rootItemId - This is CountryState root folder item id.

language - This is selected country language code. For example en-US is the code for USA English site.

templates - This is State item template id.

Sitecore Structure to maintain the Country wise State List:


 

The Country template have one Language Code field which populate all the supported language list.

Each country item will contain the list of states as key value pair.

GraphQL to fetch country wise state list from Next JS application

query CountryStateDropDownList($rootItemId: String!, $language: String!, $templates: String!) {
  search(
    where: {
      AND: [
        { name: "_path", value: $rootItemId, operator: CONTAINS }
        { name: "_templates", value: $templates, operator: CONTAINS }
        { name: "languageCode", value: $language, operator: EQ }
      ]
    }
  ) {
    results {
       language {
            name           
          }
      children {
     stateList:   results {
         stateName: name         
          key: field(name: "key") {
            value
          }
          displayText: field(name: "value") {
            value
          }
        }
      }
    }
  }
}

Query Variables:
{

  "rootItemId": "{25A60222-F59C-4FC1-8256-F1ED4B05D7F3}",

  "language": "en-GB",

  "templates": "{35AEC51F-2CDC-4A8A-86FF-48640ECDDACA}"

Result screenshot:





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