Get i18n language from Async Storage

Viewed 210

I am using i18n to translate a React Native app. In i18n.js file:


const getLang = async () => {
  const language = await AsyncStorage.getItem("locale");
  // console.log(`language |==> `, language);
  return "pt";
};

// passes i18n down to react-i18next
i18n.use(initReactI18next).init({
  resources: {
    en,
    pt,
  },
  lng: getLang(),  // getting language from local storage
  interpolation: {
    escapeValue: false,
  },
  react: { useSuspense: false },
});

export default i18n;

using getLang() function I try to access Async Storage and get the user's selected language, but I am getting the below error:

enter image description here

I couldn't copy-paste the error, so this is the error I get in the simulator. How do I resolve above stated issue?

Thank You

1 Answers

Because i was looking for help but couldn't find any, i did the following. In use({}) added a custom languageDetector:

i18n
  .use(initReactI18next)
  .use({
    type: 'languageDetector',
    name: 'customDetector',
    async: true, // If this is set to true, your detect function receives a callback function that you should call with your language, useful to retrieve your language stored in AsyncStorage for example
    init: function () {
      /* use services and options */
    },
    detect: function (callback: (val: string) => void) {
      console.log('[LANG] detecting language');
      AsyncStorage.getItem('LANG').then((val: string | null) => {
        const detected = val || fallbackLanguage;
        console.log('[LANG] detected:', detected);
        callback(detected);
      });
    },
    cacheUserLanguage: function (lng: string) {
      return lng;
    },
  })
  .init({
    resources,
    fallbackLng: fallbackLanguage,

    interpolation: {
      escapeValue: false, // react already safes from xss
    },
    returnObjects: true,
    debug: true,
    // react-i18next options
    react: {
      useSuspense: true,
    },
    detection: {
      order: ['customDetector'],
    },
  })
  .then(() => console.log('[INIT] i18n initialized'));

Note it's important the detection.order part because it won't be called otherwise.

Related