Fetch dictionary data using a custom REST data fetcher

Version:

The RestDictionaryServiceConfig type accepts a dataFetcher property. You can use this property to pass a custom data fetcher to your instance of the Dictionary Service. By default, the JSS REST Dictionary service uses the NativeDataFetcher.

Note

This example assumes you create the files in the root directory of the application and that you have a config.js file in that same directory. Adjust the import statements as necessary to reflect your project's setup.

To use a REST dictionary service with a custom data fetcher:

  1. In a dictionary-service.ts file, create an instance of the RestDictionaryService class and provide the configuration object:

    • For JSS version 22.4 or later, use NativeDataFetcher:

      import { 
        NativeDataFetcher,
        NativeDataFetcherResponse,
        RestDictionaryService,
        DictionaryServiceData
      } from '@sitecore-jss/sitecore-jss';
      import config from './config';
      // define your custom data fetcher
      function dataFetcher(url: string, data?: RequestInit): Promise<NativeDataFetcherResponse<DictionaryServiceData>> {
        return new NativeDataFetcher().fetch(url, data);
      }
      export const dictionaryService = new RestDictionaryService({
        apiHost: config.sitecoreApiHost,
        apiKey: config.sitecoreApiKey,
        siteName: config.jssAppName,
        // provide your custom data fetcher to the service instance
        dataFetcher
      });
    • For JSS version 22.3 or earlier, use AxiosDataFetcher:

      import { AxiosResponse } from 'axios';
      import { 
        AxiosDataFetcher,
        RestDictionaryService,
        DictionaryServiceData
      } from '@sitecore-jss/sitecore-jss';
      import config from './config';
      
      // define your custom data fetcher
      function dataFetcher(url: string, data?: unknown): Promise<AxiosResponse<DictionaryServiceData>> {
        return new AxiosDataFetcher().fetch(url, data);
      }
      
      export const dictionaryService = new RestDictionaryService({
        apiHost: config.sitecoreApiHost,
        apiKey: config.sitecoreApiKey,
        siteName: config.jssAppName,
        // provide your custom data fetcher to the service instance
        dataFetcher
      });
  2. Import and use the new dictionary service:

    import { dictionaryService } from './dictionary-service';
    
    const language = 'en';
    
    dictionaryService.fetchDictionaryData(language).then(data => {
         // do something with the data
    });
If you have suggestions for improving this article, let us know!