diff --git a/examples/nextjs-13/src/i18n.ts b/examples/nextjs-13/src/i18n.ts index 493ea13..95b176b 100644 --- a/examples/nextjs-13/src/i18n.ts +++ b/examples/nextjs-13/src/i18n.ts @@ -1,5 +1,7 @@ -import { i18n } from '@lingui/core'; +import { i18n, Messages } from '@lingui/core'; import { en, cs } from 'make-plural/plurals'; +import { useRef, useEffect } from 'react'; +import { useRouter } from 'next/router'; export const locales = [ { twoLettersCode: 'en', label: 'English' }, @@ -18,8 +20,24 @@ export async function loadCatalog(locale: string) { } -// If not we can just load all the catalogs and do a simple i18n.active(localeToActive) -// i18n.load({ -// en: messagesEn, -// cs: messagesCs, -// }); +export function useLinguiInit(messages: Messages) { + const router = useRouter() + const locale = router.locale || router.defaultLocale! + const firstRender = useRef(true) + + // run only once on the first render (for server side) + if (messages && firstRender.current) { + i18n.load(locale, messages) + i18n.activate(locale) + firstRender.current = false + } + + useEffect(() => { + if (messages) { + i18n.load(locale, messages) + i18n.activate(locale) + } + }, [locale, messages]) + + return i18n; +} diff --git a/examples/nextjs-13/src/pages/_app.tsx b/examples/nextjs-13/src/pages/_app.tsx index 2c45ed7..89b357e 100644 --- a/examples/nextjs-13/src/pages/_app.tsx +++ b/examples/nextjs-13/src/pages/_app.tsx @@ -1,18 +1,10 @@ import '@/styles/globals.css'; import type { AppProps } from 'next/app'; -import { i18n } from '@lingui/core'; import { I18nProvider } from '@lingui/react'; +import { useLinguiInit } from '../i18n'; export default function MyApp({ Component, pageProps, router }: AppProps) { - // Warning! THis is not public api, I didn't find a way how to make it better for now. - // Ususaly you have to call i18n.loadLocaleData() and i18n.activate() - // But they both dispatch a `change` event which trigger a stateChange - // and cause error in React because react still rendering current component - i18n._messages[router.locale as string] = pageProps.i18n; - i18n._locale = router.locale as string; - - // i18n.loadLocaleData(router.locale as string, pageProps.i18n); - // i18n.activate(router.locale as string); + const i18n = useLinguiInit(pageProps.i18n); return (