Refactor i18n settings and improve language load handling

This update separates the creation of i18n settings into its own function (@kit/i18n) and enhances the handling of language and namespace loading in i18n.client. It tracks loaded languages and namespaces, and prevents rendering if none are loaded or after a maximum number of iterations. The usage of Suspense has also been modified in root-providers to employ a null fallback.
This commit is contained in:
giancarlo
2024-04-21 18:40:12 +08:00
parent b1f2e435aa
commit ae10f7b142
7 changed files with 96 additions and 34 deletions

View File

@@ -1,7 +1,10 @@
'use client';
import { useSuspenseQuery } from '@tanstack/react-query';
import type { InitOptions } from 'i18next';
import type { InitOptions, i18n } from 'i18next';
import { initializeI18nClient } from './i18n.client';
let i18nInstance: i18n;
type Resolver = (
lang: string,
@@ -28,20 +31,17 @@ export function I18nProvider({
* @param resolver
*/
function useI18nClient(settings: InitOptions, resolver: Resolver) {
return useSuspenseQuery({
queryKey: ['i18n', settings.lng],
queryFn: async () => {
const isBrowser = typeof window !== 'undefined';
if (
!i18nInstance ||
i18nInstance.language !== settings.lng ||
i18nInstance.options.ns?.length !== settings.ns?.length
) {
throw loadI18nInstance(settings, resolver);
}
if (isBrowser) {
const { initializeI18nClient } = await import('./i18n.client');
return await initializeI18nClient(settings, resolver);
} else {
const { initializeServerI18n } = await import('./i18n.server');
return await initializeServerI18n(settings, resolver);
}
},
});
return i18nInstance;
}
async function loadI18nInstance(settings: InitOptions, resolver: Resolver) {
i18nInstance = await initializeI18nClient(settings, resolver);
}