Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: reset t when keyPrefix is updated. #1544

Merged
merged 2 commits into from Aug 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/useTranslation.js
Expand Up @@ -101,7 +101,7 @@ export function useTranslation(ns, props = {}) {
setT(getT);
}
isInitial.current = false;
}, [i18n]); // re-run when i18n instance was replaced
}, [i18n, keyPrefix]); // re-run when i18n instance or keyPrefix were replaced

const ret = [t, i18n, ready];
ret.t = t;
Expand Down
23 changes: 16 additions & 7 deletions test/useTranslation.spec.js
Expand Up @@ -115,15 +115,24 @@ describe('useTranslation', () => {
});

describe('key prefix', () => {
i18nInstance.addResource('en', 'translation', 'deeply.nested.key', 'here!');
i18nInstance.addResource('en', 'translation', 'deeply.nested_a.key', 'here_a!');
i18nInstance.addResource('en', 'translation', 'deeply.nested_b.key', 'here_b!');

it('should apply keyPrefix', () => {
const { result } = renderHook(() =>
useTranslation('translation', { i18n: i18nInstance, keyPrefix: 'deeply.nested' }),
it('should apply keyPrefix and reset it once changed', () => {
let keyPrefix = 'deeply.nested_a';
const { result, rerender } = renderHook(() =>
useTranslation('translation', { i18n: i18nInstance, keyPrefix }),
);
const { t } = result.current;
expect(t('key')).toBe('here!');
expect(t.keyPrefix).toBe('deeply.nested');
const { t: t1 } = result.current;
expect(t1('key')).toBe('here_a!');
expect(t1.keyPrefix).toBe('deeply.nested_a');

keyPrefix = 'deeply.nested_b';
rerender();

const { t: t2 } = result.current;
expect(t2('key')).toBe('here_b!');
expect(t2.keyPrefix).toBe('deeply.nested_b');
});
});

Expand Down