Skip to content

Commit

Permalink
fix: Return up-to-date translations when messages change (#199)
Browse files Browse the repository at this point in the history
  • Loading branch information
amannn committed Feb 20, 2023
1 parent 1ff7bcf commit 78f39b4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 12 deletions.
26 changes: 14 additions & 12 deletions packages/use-intl/src/core/createBaseTranslator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -170,23 +170,25 @@ export default function createBaseTranslator<
}
const messages = messagesOrError;

const cacheKey = [namespace, key].filter((part) => part != null).join('.');
let message;
try {
message = resolvePath(messages, key, namespace);
} catch (error) {
return getFallbackFromErrorAndNotify(
key,
IntlErrorCode.MISSING_MESSAGE,
(error as Error).message
);
}

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

let messageFormat;
if (cachedFormatsByLocale?.[locale]?.[cacheKey]) {
messageFormat = cachedFormatsByLocale?.[locale][cacheKey];
} else {
let message;
try {
message = resolvePath(messages, key, namespace);
} catch (error) {
return getFallbackFromErrorAndNotify(
key,
IntlErrorCode.MISSING_MESSAGE,
(error as Error).message
);
}

if (typeof message === 'object') {
return getFallbackFromErrorAndNotify(
key,
Expand Down
21 changes: 21 additions & 0 deletions packages/use-intl/test/react/useTranslations.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,27 @@ it('utilizes a cache for parsing messages', () => {
).toEqual(1);
});

it('updates translations when the messages on the provider change', () => {
function Component() {
const t = useTranslations();
return <>{t('message')}</>;
}

const {rerender} = render(
<IntlProvider locale="en" messages={{message: 'One'}}>
<Component />
</IntlProvider>
);
screen.getByText('One');

rerender(
<IntlProvider locale="en" messages={{message: 'Two'}}>
<Component />
</IntlProvider>
);
screen.getByText('Two');
});

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

0 comments on commit 78f39b4

Please sign in to comment.