From 4fe470a2f0d04e416318f30aa48de5a85be337f2 Mon Sep 17 00:00:00 2001 From: halouvi Date: Mon, 15 Aug 2022 11:28:31 +0300 Subject: [PATCH 1/2] reset `t` when `keyPrefix` changes --- src/useTranslation.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/useTranslation.js b/src/useTranslation.js index efc6e1f7..33a97e10 100644 --- a/src/useTranslation.js +++ b/src/useTranslation.js @@ -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; From aef6a378175d6293bf3f829a05573824b2473ae3 Mon Sep 17 00:00:00 2001 From: halouvi Date: Mon, 15 Aug 2022 12:13:59 +0300 Subject: [PATCH 2/2] add test for dynamic `keyPrefix` --- test/useTranslation.spec.js | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/test/useTranslation.spec.js b/test/useTranslation.spec.js index fb98e214..152d43b5 100644 --- a/test/useTranslation.spec.js +++ b/test/useTranslation.spec.js @@ -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'); }); });