Skip to content

Translations API

API used to perform actions related to language selection, translation, and subscribing to language change events.

classDiagram
direction LR
    TranslationsAPI --> selectedLanguage
    TranslationsAPI --> changeLanguage
    TranslationsAPI --> translate
    TranslationsAPI --> subscribeOnLanguageChange

    class TranslationsAPI {
        selectedLanguage() TLocaleIsoUnderscore
        changeLanguage(lang: TLocaleIsoUnderscore) Promise~void~
        translate(key: TranslationKeys, options?: TTranslationOptions) string
        subscribeOnLanguageChange(callback: () => void) TUnsubscribeCallback
    }

    link selectedLanguage "../methods/selected-language/"
    link changeLanguage "../methods/change-language/"
    link translate "../methods/translate/"
    link subscribeOnLanguageChange "../methods/subscribe-on-language-change/"

Get API

To get the Translations API use its name TranslationsApi with the getApi method. Note that the method is asynchronous and you will need to await it.

useStorefront(async (storefront) => {
    const translationsApi = await storefront.getApi('TranslationsApi');
});

You can also get it synchronously with the getApiSync method:

useStorefront(async (storefront) => {
    const translationsApi = storefront.getApiSync('TranslationsApi');
});

but depending on where do you use it the Translations API may not be initialized yet and it is recommended to use the getApi method to make sure it will be fetched properly.

Methods

  • selectedLanguage - get a currently selected language in the shop
  • changeLanguage - change a current language in the shop
  • translate - translate a given text based on the provided translation key and the currently selected language
  • subscribeOnLanguageChange - subscribe to language change events and fire a callback function whenever such event occurs

Example

In this example we make a TranslationsApi call to get a currently selected language in the shop.

useStorefront(async (storefront) => {
    const translationsApi = await storefront.getApi('TranslationsApi');

    const currentlySelectedLanguage = translationsApi.selectedLanguage();
});

Example

In this example we make a TranslationsApi call to translate a phrase.

useStorefront(async (storefront) => {
    const translationsApi = await storefront.getApi('TranslationsApi');

    const translatedPhrase = translationsApi.translate('Example phrase');
});

Example

In this example we make a TranslationsApi call to listen to the language change event.

useStorefront(async (storefront) => {
    const translationsApi = await storefront.getApi('TranslationsApi');

    const myCallback = () => {
        alert('Language changed!');
    }

    const unsubscribeFromLanguageChange = translationsApi.subscribeOnLanguageChange(myCallback);

    // at the end
    unsubscribeFromLanguageChange();
});

Objects Reference