Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update nextjs example #38

Merged
merged 1 commit into from
Mar 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions examples/nextjs-13/src/i18n.ts
Original file line number Diff line number Diff line change
@@ -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' },
Expand All @@ -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;
}
12 changes: 2 additions & 10 deletions examples/nextjs-13/src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<I18nProvider i18n={i18n}>
Expand Down