Enable suspense mode for i18n library

The changes introduce suspense mode in the i18n settings, waiting until all languages are loaded. The loading state now shows a global loading
This commit is contained in:
giancarlo
2024-04-16 21:46:18 +08:00
parent 85ad61c20e
commit eea6f8121a
3 changed files with 18 additions and 15 deletions

5
apps/web/app/loading.tsx Normal file
View File

@@ -0,0 +1,5 @@
import { GlobalLoader } from '@kit/ui/global-loader';
export default function Loading() {
return <GlobalLoader displaySpinner={false} />;
}

View File

@@ -61,5 +61,8 @@ export function getI18nSettings(
fallbackNS: defaultI18nNamespaces,
defaultNS: defaultI18nNamespaces,
ns,
react: {
useSuspense: true,
},
};
}

View File

@@ -14,20 +14,24 @@ export async function initializeI18nClient(
settings: InitOptions,
resolver: (lang: string, namespace: string) => Promise<object>,
): Promise<i18n> {
if (clientInstance?.isInitialized) {
if (clientInstance) {
return Promise.resolve(clientInstance);
}
const loadedLanguages: string[] = [];
await i18next
.use(initReactI18next)
.use(
resourcesToBackend(async (language, namespace, callback) => {
const data = await resolver(language, namespace);
loadedLanguages.push(language);
return callback(null, data);
}),
)
.use(LanguageDetector)
.use(initReactI18next)
.init(
{
...settings,
@@ -47,19 +51,10 @@ export async function initializeI18nClient(
},
);
console.log('i18n client initialized');
console.log(
`initialized with ${i18next.languages.join(', ')} languages`,
clientInstance,
);
console.log(
'resource',
i18next.getResource('en', 'billing', 'billingInterval.month'),
);
console.log(i18next.t('billing:billingInterval.month'));
// keep component suspended until all languages are loaded
if (loadedLanguages.length !== settings.ns?.length) {
throw new Error();
}
clientInstance = i18next;