Legeo
Legeo

Reputation: 792

i18n translate text in a function

I'm having some problem to translate some error message outside a components.

this is my i18n setting

const languageDetector = {
  type: 'languageDetector',
  async: true,
  detect: (cb: (baseLanguage: string) => void) => {
    let prevLanguage: string;
    store.subscribe(() => {
      const selectBaseLanguage = makeSelectBaseLanguage();
      const baseLanguage = selectBaseLanguage(store.getState());
      if (baseLanguage !== prevLanguage) {
        prevLanguage = baseLanguage;
        cb(baseLanguage);
      }
    });
  },
  init: () => {},
  cacheUserLanguage: () => {},
};

i18n
  .use(languageDetector)
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    debug: true,
    resources: languagesResources,
    // language to use if translations in user language are not available.
    fallbackLng: defaultLanguage,
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },

    react: {
      wait: false,
      useSuspense: false,
    },
  });

i've to reach the errors code in this file ----> httpErrors: en_HttpError

path file : @config/locales/languageConfig

export const languagesResources = {
  en: { ...en, httpErrors: en_HttpError },
  tr: { ...tr, httpErrors: tr_HttpError },
};

and this is the function* where i need to reach the traduction:

path file : @config/utils/helpers

export function* _handleFetchError(error: any) {
  const { httpStatus, httpDescriptions, errorCode, errorDescription } = error;
  console.log('!!! Start Error Handler !!!:', httpStatus, httpDescriptions, errorCode, errorDescription);

  const test = i18n.t('en_HttpError');

  yield put(sagaShowFullScreenOverlay(GenericOverlay, errorModal));
}

right now with the const test i obtain only an undefined error,

How can i obtain the right traduction based on the errorCode value that I receive without have an undefined error ?

Upvotes: 0

Views: 2738

Answers (1)

Abel Matos
Abel Matos

Reputation: 96

I would need more info about your error, but you maybe want to do something like that: i18next Fallback. So you can show a message that depends of httpStatus response like error.404 as Página no encontrada

Considerate your i18n.t function waits a text key for a registered translation.

In my simple case:

i18n.init({
    fallbackLng: {
        default: ['es'],
    },
    resources: {
        es: {
            common: {
                Name: 'Nombre',
....

Then, I can do i18n.t('Name') for get 'Nombre'

Upvotes: 3

Related Questions