Skip to content

Commit

Permalink
fix(next-international): locales switching on Pages Router (#352)
Browse files Browse the repository at this point in the history
  • Loading branch information
QuiiBz committed Feb 10, 2024
1 parent a071c1f commit 88bfe23
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 29 deletions.
16 changes: 2 additions & 14 deletions packages/next-international/src/common/create-use-i18n.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,17 @@
import type { Context } from 'react';
import { useContext } from 'react';
import { useContext, useMemo } from 'react';
import type { BaseLocale } from 'international-types';
import type { LocaleContext } from '../types';
import { createT } from './create-t';

export function createUsei18n<Locale extends BaseLocale>(I18nClientContext: Context<LocaleContext<Locale> | null>) {
const localeCache = new Map<string, ReturnType<typeof createT<Locale, undefined>>>();

return function useI18n() {
const context = useContext(I18nClientContext);

if (!context) {
throw new Error('`useI18n` must be used inside `I18nProvider`');
}

const cached = localeCache.get(context.locale);

if (cached) {
return cached;
}

const localeFn = createT(context, undefined);

localeCache.set(context.locale, localeFn);

return localeFn;
return useMemo(() => createT(context, undefined), [context]);
};
}
17 changes: 2 additions & 15 deletions packages/next-international/src/common/create-use-scoped-i18n.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,19 @@
import type { Context } from 'react';
import { useContext } from 'react';
import { useContext, useMemo } from 'react';
import type { BaseLocale, Scopes } from 'international-types';
import type { LocaleContext } from '../types';
import { createT } from '../common/create-t';

export function createScopedUsei18n<Locale extends BaseLocale>(
I18nClientContext: Context<LocaleContext<Locale> | null>,
) {
const localeCache = new Map<string, ReturnType<typeof createT<Locale, undefined>>>();

return function useScopedI18n<Scope extends Scopes<Locale>>(scope: Scope): ReturnType<typeof createT<Locale, Scope>> {
const context = useContext(I18nClientContext);

if (!context) {
throw new Error('`useI18n` must be used inside `I18nProvider`');
}

const cacheKey = `${context.locale}-${scope}`;
const cached = localeCache.get(cacheKey);

if (cached) {
return cached;
}

const localeFn = createT(context, scope);

localeCache.set(cacheKey, localeFn);

return localeFn;
return useMemo(() => createT(context, scope), [context, scope]);
};
}

0 comments on commit 88bfe23

Please sign in to comment.