diff --git a/packages/experience/src/Providers/SettingsProvider/use-preview.ts b/packages/experience/src/Providers/SettingsProvider/use-preview.ts index 3fad4e60d..4629c4534 100644 --- a/packages/experience/src/Providers/SettingsProvider/use-preview.ts +++ b/packages/experience/src/Providers/SettingsProvider/use-preview.ts @@ -13,18 +13,17 @@ const usePreview = () => { // Fetch the preview config useEffect(() => { - // Init i18n - const i18nInit = initI18n(); - // Listen to the message from the ancestor window const previewMessageHandler = async (event: MessageEvent) => { // #event.data should be guarded at the provider's side if (event.data.sender === 'ac_preview') { - // Wait for i18n to be initialized - await i18nInit; - // eslint-disable-next-line no-restricted-syntax - setPreviewConfig(event.data.config as PreviewConfig); + const previewConfig = event.data.config as PreviewConfig; + + // Wait for i18n to be initialized + await initI18n(previewConfig.language); + + setPreviewConfig(previewConfig); } }; diff --git a/packages/experience/src/i18n/init.ts b/packages/experience/src/i18n/init.ts index 80b67604a..93f0cc454 100644 --- a/packages/experience/src/i18n/init.ts +++ b/packages/experience/src/i18n/init.ts @@ -4,8 +4,11 @@ import { initReactI18next } from 'react-i18next'; import { getI18nResource } from '@/i18n/utils'; -const initI18n = async () => { - const { resources, lng } = await getI18nResource(); +// Call once globally +i18next.use(initReactI18next); + +const initI18n = async (initialLanguage?: string) => { + const { resources, lng } = await getI18nResource(initialLanguage); const options: InitOptions = { resources, @@ -15,12 +18,14 @@ const initI18n = async () => { }, }; - i18next.use(initReactI18next); - const i18n = i18next.init(options); - // @ts-expect-error - i18next doesn't have a type definition for this. Must called after i18next is initialized - i18next.services.formatter.add('zhOrSpaces', (value: string, lng) => { + /** + * Note + * - Must call after i18next is initialized + * - Don't worry to call this multiple times, i18next will replace the formatter if it's already added. + */ + i18next.services.formatter?.add('zhOrSpaces', (value: string, lng) => { if (lng !== 'zh-CN') { return value; }