feat: improve instantiation of intl
This commit is contained in:
@@ -2,11 +2,21 @@
|
||||
|
||||
import { IntlProvider } from "react-intl"
|
||||
|
||||
import type { ServerIntlProviderProps } from "@/types/i18n"
|
||||
import type { ClientIntlProviderProps } from "@/types/i18n"
|
||||
|
||||
export default function ServerIntlProvider({
|
||||
export default function ClientIntlProvider({
|
||||
children,
|
||||
intl,
|
||||
}: ServerIntlProviderProps) {
|
||||
return <IntlProvider {...intl}>{children}</IntlProvider>
|
||||
locale,
|
||||
defaultLocale,
|
||||
messages,
|
||||
}: ClientIntlProviderProps) {
|
||||
return (
|
||||
<IntlProvider
|
||||
locale={locale}
|
||||
defaultLocale={defaultLocale}
|
||||
messages={messages}
|
||||
>
|
||||
{children}
|
||||
</IntlProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,32 +1,36 @@
|
||||
import "server-only"
|
||||
|
||||
import { createIntl, createIntlCache } from "@formatjs/intl"
|
||||
import { headers } from "next/headers"
|
||||
|
||||
import { Lang } from "@/constants/languages"
|
||||
|
||||
import { getLang } from "@/i18n/serverContext"
|
||||
|
||||
import type { IntlShape } from "react-intl"
|
||||
|
||||
const cache = createIntlCache()
|
||||
|
||||
export async function initIntl(lang: Lang) {
|
||||
return createIntl<React.ReactNode>(
|
||||
{
|
||||
defaultLocale: Lang.en,
|
||||
locale: lang,
|
||||
messages: (await import(`./dictionaries/${lang}.json`)).default,
|
||||
},
|
||||
cache
|
||||
)
|
||||
const instances: Partial<Record<Lang, IntlShape>> = {}
|
||||
|
||||
export async function getMessages(lang: Lang): Promise<Record<string, string>> {
|
||||
return (await import(`./dictionaries/${lang}.json`)).default
|
||||
}
|
||||
|
||||
export async function getIntl(forceLang?: Lang) {
|
||||
const h = headers()
|
||||
let lang = h.get("x-lang") as Lang
|
||||
if (!lang) {
|
||||
lang = Lang.en
|
||||
export async function getIntl() {
|
||||
const lang = getLang()
|
||||
|
||||
if (!instances[lang]) {
|
||||
const messages = await getMessages(lang)
|
||||
instances[lang] = createIntl<React.ReactNode>(
|
||||
{
|
||||
defaultLocale: Lang.en,
|
||||
locale: lang,
|
||||
messages,
|
||||
},
|
||||
cache
|
||||
)
|
||||
}
|
||||
|
||||
if (forceLang) {
|
||||
return await initIntl(forceLang)
|
||||
}
|
||||
return await initIntl(lang)
|
||||
// Exclamation mark can be removed once we update TS to 5.8.2+
|
||||
return instances[lang]!
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user