Skip to content

Commit

Permalink
fix: execute import function in I18nProviderWrapper instead of `I18…
Browse files Browse the repository at this point in the history
…nProvider`
  • Loading branch information
Yovach committed Dec 20, 2023
1 parent c697a30 commit db71913
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 24 deletions.
10 changes: 2 additions & 8 deletions examples/next-app/locales/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,8 @@ import { createI18nClient } from 'next-international/client';
export const { useI18n, useScopedI18n, I18nProviderClient, useChangeLocale, defineLocale, useCurrentLocale } =
createI18nClient(
{
en: async () => {
await new Promise(resolve => setTimeout(resolve, 100));
return import('./en');
},
fr: async () => {
await new Promise(resolve => setTimeout(resolve, 100));
return import('./fr');
},
en: () => import('./en'),
fr: () => import('./fr'),
},
{
// Uncomment to set base path
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ type I18nProviderWrapperProps = {
locale: string;
fallback?: ReactNode;
children: ReactNode;

importLocale: Promise<Record<string, unknown>>;
};

export const localesCache = new Map<string, Record<string, unknown>>();
Expand All @@ -21,21 +23,9 @@ export function createI18nProviderClient<Locale extends BaseLocale>(
locales: ImportedLocales,
fallbackLocale?: Record<string, unknown>,
) {
function I18nProvider({ locale, children }: I18nProviderProps) {
let clientLocale: any = localesCache.get(locale);

if (!clientLocale) {
const newLocale = locales[locale as keyof typeof locales];

if (!newLocale) {
error(`The locale '${locale}' is not supported. Defined locales are: [${Object.keys(locales).join(', ')}].`);
notFound();
}

clientLocale = use(newLocale()).default;
localesCache.set(locale, clientLocale);
}

function I18nProvider({ locale, importLocale, children }: I18nProviderProps) {
const clientLocale = use(importLocale).default as Record<string, unknown>;
localesCache.set(locale, clientLocale);
const value = useMemo(
() => ({
localeContent: flattenLocale<Locale>(clientLocale),
Expand All @@ -49,9 +39,17 @@ export function createI18nProviderClient<Locale extends BaseLocale>(
}

return function I18nProviderWrapper({ locale, fallback, children }: I18nProviderWrapperProps) {
const importFnLocale = locales[locale as keyof typeof locales];
if (!importFnLocale) {
error(`The locale '${locale}' is not supported. Defined locales are: [${Object.keys(locales).join(', ')}].`);
notFound();
}

return (
<Suspense fallback={fallback}>
<I18nProvider locale={locale}>{children}</I18nProvider>
<I18nProvider locale={locale} importLocale={importFnLocale()}>
{children}
</I18nProvider>
</Suspense>
);
};
Expand Down

0 comments on commit db71913

Please sign in to comment.