UNPKG

ra-core

Version:

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

48 lines 2 kB
import * as React from 'react'; import { useEffect, useState } from 'react'; import { I18nContext } from "./I18nContext.js"; import { useStore } from "../store/useStore.js"; import { useNotify } from "../notification/index.js"; /** * Store the i18nProvider in a context, and rerender children when the locale changes */ export const I18nContextProvider = ({ value = defaulti18nContext, children, }) => { const [locale] = useStore('locale'); const notify = useNotify(); const [key, setKey] = useState(0); // to avoid blinking effect, delay first render if the user has a non-default locale const [isInitialized, setInitialized] = useState(locale === value.getLocale()); // watch store for locale changes useEffect(() => { if (locale && value.getLocale() !== locale) { new Promise(resolve => { // so we systematically return a Promise for the messages // i18nProvider may return a Promise for language changes, resolve(value.changeLocale(locale)); }) .then(() => { // 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(key => key + 1); setInitialized(true); }) .catch(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; }; const defaulti18nContext = { translate: x => x, changeLocale: () => Promise.resolve(), getLocale: () => 'en', }; //# sourceMappingURL=I18nContextProvider.js.map