Skip to content

Commit

Permalink
fix: reset t when keyPrefix is updated. (#1544)
Browse files Browse the repository at this point in the history
* reset `t` when `keyPrefix` changes

* add test for dynamic `keyPrefix`
  • Loading branch information
halouvi committed Aug 15, 2022
1 parent ef3b87a commit c06710c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
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

0 comments on commit c06710c

Please sign in to comment.