8

I use react-i18next and i18next to localize an app. I want to be able to change the language manually in the settings and persist that change. The problem is i dont know how to use redux in the i18n config file as redux is async, also i've checked the docs for some built in storage option in react-i18next but without success.

here is the i18n config file:

'use strict';

import i18n from 'i18next';
import {reactI18nextModule, initReactI18next} from 'react-i18next';
import DeviceInfo from 'react-native-device-info';

import translationFR from '../translation/fr/translation.json';
import translationEN from '../translation/en/translation.json';
import translationAR from '../translation/ar/translation.json';

async function getAppLang() {
  const unsubscribe = store.subscribe(() => true);
  const appLang = await store.getState().appLang;
  await unsubscribe();
  return appLang;
}

let locale = DeviceInfo.getDeviceLocale().substring(0, 2);
if (locale != 'fr' && locale != 'ar') {
  locale = 'en';
}

// the translations
const resources = {
  en: translationEN,
  fr: translationFR,
  ar: translationAR,
};
i18n
  .use(reactI18nextModule) // passes i18n down to react-i18next
  .init({
    resources: resources,
    lng: locale,
    fallbackLng: ['en', 'fr', 'ar'],
    keySeparator: false, // we do not use keys in form messages.welcome
    interpolation: {
      escapeValue: false, // react already safes from xss
    },
  });


export default i18n;

To change the language i use this function:

import i18n from 'config/i18n';
////
i18n.changeLanguage(langageName);

THANKS !

B. Mohammad
  • 2,152
  • 1
  • 13
  • 28
  • Do you mean by "store" to store is inside redux-store? or persist it between app starts? – felixmosh May 10 '20 at 20:51
  • to persist it between app starts – B. Mohammad May 11 '20 at 01:05
  • How do you persist your redux store? If at all? – felixmosh May 11 '20 at 06:32
  • i use `redux-persist`. The workaround i found for now is to load stored lang manually on app launch. It work ok it's not noticeable – B. Mohammad May 12 '20 at 14:05
  • 1
    I try to achieve a similar feature, I use redux-persist to store my language. But where do you call the i18n.changeLanguage() with the persisted language ? I tried to do that in the componentDidMount() of my main "App" component, but it does not re-render... – marcel f Oct 28 '20 at 11:49

0 Answers0