Fetch dictionary data using a custom REST data fetcher
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
.
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:
-
In a
dictionary-service.ts
file, create an instance of theRestDictionaryService
class and provide the configuration object:-
For JSS version 22.4 or later, use
NativeDataFetcher
:RequestResponseimport { 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
:RequestResponseimport { 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 });
-
-
Import and use the new dictionary service:
RequestResponseimport { dictionaryService } from './dictionary-service'; const language = 'en'; dictionaryService.fetchDictionaryData(language).then(data => { // do something with the data });