Skip to content

Commit

Permalink
fix: Render correct messages when the namespace changes in `useTransl…
Browse files Browse the repository at this point in the history
…ations` (#58)

* include namespace in cacheKey

* add a test for cacheing by namespace

* Improve naming for test

The caching should be a implementation detail here

Co-authored-by: Jan Amann <jan@amann.me>

* Handle undefined namespace or key in cacheKey

* fix linter issues with useTranslation hook after adding namespace to cache key

Co-authored-by: Jan Amann <jan@amann.me>
  • Loading branch information
mismosmi and amannn committed Sep 17, 2021
1 parent 08af70d commit b8f7dab
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
10 changes: 7 additions & 3 deletions packages/use-intl/src/useTranslations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,13 @@ export default function useTranslations(namespace?: string) {
}
const messages = messagesOrError;

const cacheKey = [namespace, key]
.filter((part) => part != null)
.join('.');

let messageFormat;
if (cachedFormatsByLocale[locale]?.[key]) {
messageFormat = cachedFormatsByLocale[locale][key];
if (cachedFormatsByLocale[locale]?.[cacheKey]) {
messageFormat = cachedFormatsByLocale[locale][cacheKey];
} else {
let message;
try {
Expand Down Expand Up @@ -201,7 +205,7 @@ export default function useTranslations(namespace?: string) {
if (!cachedFormatsByLocale[locale]) {
cachedFormatsByLocale[locale] = {};
}
cachedFormatsByLocale[locale][key] = messageFormat;
cachedFormatsByLocale[locale][cacheKey] = messageFormat;
}

try {
Expand Down
29 changes: 29 additions & 0 deletions packages/use-intl/test/useTranslations.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,35 @@ it('has a stable reference', () => {
screen.getByText('2');
});

it('renders the correct message when the namespace changes', () => {
function Component({namespace}: {namespace: string}): JSX.Element {
const t = useTranslations(namespace);

return <span>{t('title')}</span>;
}

const messages = {
namespaceA: {title: 'This is namespace A'},
namespaceB: {title: 'This is namespace B'}
};

const {rerender} = render(
<IntlProvider locale="en" messages={messages}>
<Component namespace="namespaceA" />
</IntlProvider>
);

screen.getByText('This is namespace A');

rerender(
<IntlProvider locale="en" messages={messages}>
<Component namespace="namespaceB" />
</IntlProvider>
);

screen.getByText('This is namespace B');
});

describe('t.rich', () => {
function renderRichTextMessage(
message: string,
Expand Down

0 comments on commit b8f7dab

Please sign in to comment.