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:
@@ -3,6 +3,12 @@ import LanguageDetector from 'i18next-browser-languagedetector';
|
||||
import resourcesToBackend from 'i18next-resources-to-backend';
|
||||
import { initReactI18next } from 'react-i18next';
|
||||
|
||||
// Keep track of the number of iterations
|
||||
let iteration = 0;
|
||||
|
||||
// Maximum number of iterations
|
||||
const MAX_ITERATIONS = 20;
|
||||
|
||||
/**
|
||||
* Initialize the i18n instance on the client.
|
||||
* @param settings - the i18n settings
|
||||
@@ -12,11 +18,22 @@ export async function initializeI18nClient(
|
||||
settings: InitOptions,
|
||||
resolver: (lang: string, namespace: string) => Promise<object>,
|
||||
): Promise<i18n> {
|
||||
const loadedLanguages: string[] = [];
|
||||
const loadedNamespaces: string[] = [];
|
||||
|
||||
await i18next
|
||||
.use(
|
||||
resourcesToBackend(async (language, namespace, callback) => {
|
||||
const data = await resolver(language, namespace);
|
||||
|
||||
if (!loadedLanguages.includes(language)) {
|
||||
loadedLanguages.push(language);
|
||||
}
|
||||
|
||||
if (!loadedNamespaces.includes(namespace)) {
|
||||
loadedNamespaces.push(namespace);
|
||||
}
|
||||
|
||||
return callback(null, data);
|
||||
}),
|
||||
)
|
||||
@@ -41,5 +58,24 @@ export async function initializeI18nClient(
|
||||
},
|
||||
);
|
||||
|
||||
// to avoid infinite loops, we return the i18next instance after a certain number of iterations
|
||||
// even if the languages and namespaces are not loaded
|
||||
if (iteration >= MAX_ITERATIONS) {
|
||||
console.debug(`Max iterations reached: ${MAX_ITERATIONS}`);
|
||||
|
||||
return i18next;
|
||||
}
|
||||
|
||||
// keep component from rendering if no languages or namespaces are loaded
|
||||
if (loadedLanguages.length === 0 || loadedNamespaces.length === 0) {
|
||||
iteration++;
|
||||
|
||||
console.debug(
|
||||
`Keeping component from rendering if no languages or namespaces are loaded. Iteration: ${iteration}. Will stop after ${MAX_ITERATIONS} iterations.`,
|
||||
);
|
||||
|
||||
throw new Error('No languages or namespaces loaded');
|
||||
}
|
||||
|
||||
return i18next;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user