Search code examples
javascriptreactjsi18nextreact-i18next

how can I add a translationFailSafe object if i18n is unable to loadPath specified in backend?


I would like to add a failSafeLanguageMap to my i18n instance in case the backend.loadPath is not found for example.

My current initialisation is as follows:

i18n
    .use(I18NextBackend)
    .use(initReactI18next)
    .init({
      lng: langs.selectedLanguage,
      fallbackLng: 'en',
      debug: process.env.NODE_ENV === 'development',
      keySeparator: false,
      interpolation: {
        escapeValue: false,
      },
      react: {
        useSuspense: false,
      },
      backend: {
        loadPath: `some_path/locales/{{lng}}/{{ns}}.json`,
      }
    });

I would like to load failSafeLanguageMap from some json file as follows:

import failSafeLanguageMap from '/fail-safe.json';

and use this as a fail safe map in the case that backend.loadPath is not found


Solution

  • So there was an answer that pointed me in the right direction, however it seems like it's been deleted since. So basically it requires the use of a chained backend. The chain backend is initialised as follows:

    i18n
        .use(I18NextBackend)
        .use(initReactI18next)
        .init({
          lng: langs.selectedLanguage,
          fallbackLng: 'en',
          debug: process.env.NODE_ENV === 'development',
          keySeparator: false,
          interpolation: {
            escapeValue: false,
          },
          react: {
            useSuspense: false,
          },
          backend: {
            backends: [
              I18NextBackend,
              resourcesToBackend((language, namespace, callback) => {
                callback(null, failSafeLanguageMap);
              })
            ],
            backendOptions: [{
              loadPath: `some_path/locales/{{lng}}/{{ns}}.json`,
            }]
          },
        });