UNPKG

ra-core

Version:

Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React

49 lines 2.18 kB
import * as React from 'react'; import { useEffect, useState } from 'react'; import { I18nContext } from './I18nContext'; import { useStore } from '../store/useStore'; import { useNotify } from '../notification'; /** * Store the i18nProvider in a context, and rerender children when the locale changes */ export var I18nContextProvider = function (_a) { var _b = _a.value, value = _b === void 0 ? defaulti18nContext : _b, children = _a.children; var locale = useStore('locale')[0]; var notify = useNotify(); var _c = useState(0), key = _c[0], setKey = _c[1]; // to avoid blinking effect, delay first render if the user has a non-default locale var _d = useState(locale === value.getLocale()), isInitialized = _d[0], setInitialized = _d[1]; // watch store for locale changes useEffect(function () { if (locale && value.getLocale() !== locale) { new Promise(function (resolve) { // so we systematically return a Promise for the messages // i18nProvider may return a Promise for language changes, resolve(value.changeLocale(locale)); }) .then(function () { // Force full page re-render. // This is slow on locale change, but it's a good way // to avoid having one subscription to the locale // for each call to translate() setKey(function (key) { return key + 1; }); setInitialized(true); }) .catch(function (error) { setInitialized(true); notify('ra.notification.i18n_error', { type: 'error' }); console.error(error); }); } else { setInitialized(true); } }, [value, locale, notify]); return isInitialized ? (React.createElement(I18nContext.Provider, { value: value, key: key }, children)) : null; }; var defaulti18nContext = { translate: function (x) { return x; }, changeLocale: function () { return Promise.resolve(); }, getLocale: function () { return 'en'; }, }; //# sourceMappingURL=I18nContextProvider.js.map