3

What you were expecting:
Set initial locale with value from localStorage.getItem('locale_language'); instead of 'en'.

import polyglotI18nProvider from 'ra-i18n-polyglot'; // react-admin 

const i18nProvider = polyglotI18nProvider(locale => {
    if (locale === 'ru') {
        return import('./i18n/ru').then(messages => messages.default);
    }
    return englishMessages;
}, 'en'); 

What happened instead:

But when I do this there is error Error: The i18nProvider returned a Promise for the messages of the default locale (ru). Please update your i18nProvider to return the messages of the default locale in a synchronous way.

Related code:

There is how I get value from localStore

export function getLocalLanguage(): string {
    let defaultLocalLanguage = 'en';
    const storedLanguage = localStorage.getItem('locale_language');
    if (storedLanguage !== null) {
        defaultLocalLanguage = storedLanguage;
    }
    return defaultLocalLanguage;
}

There is how I set initial local for polyglotI18nProvider

const i18nProvider = polyglotI18nProvider(locale => {
    if (locale === 'ru') {
        return import('./i18n/ru').then(messages => messages.default);
    }
    return englishMessages;
}, getLocalLanguage());

Here is said localStorage is syncronous so there should be no problem then?

resolveBrowserLocale may be an alternative, but I need a more persistent way to store language.

Jasurbek Nabijonov
  • 1,607
  • 3
  • 24
  • 37

1 Answers1

3

It looks like you're setting the default locale to 'ru' when pulling from localStorage, but your import for the 'ru' strings is asynchronous.

From the documentation for ra-i18n-polyglot:

The messages for the default locale (used by react-admin for the initial render) must be returned in a synchronous way.

The example they give suggests that if you want to dynamically resolve the default (= initial) locale, you need to import all possible languages synchronously:

import englishMessages from 'ra-language-english';
import frenchMessages from 'ra-language-french';

const messages = {
    fr: frenchMessages,
    en: englishMessages,
};

const i18nProvider = polyglotI18nProvider(
    locale => messages[locale] ? messages[locale] : messages.en,
    resolveBrowserLocale()
);

Edit: more code

ATOMP
  • 1,311
  • 10
  • 29
  • 1
    Yes, it solved this problem. I thought issue was with ```localStorage```. Now I return it ```return russianMessages;``` instead of ```return import('./i18n/ru').then(messages => messages.default);```. Thank you. – Jasurbek Nabijonov Aug 24 '20 at 04:05