From ab6b93b53a46a658d713ee57616c06aeaf4de96b Mon Sep 17 00:00:00 2001 From: Zack Sunderland Date: Tue, 11 Apr 2023 07:07:06 -0600 Subject: [PATCH] Allow for falsey default values (#1021) Co-authored-by: zsunderland --- __tests__/useTranslation.test.js | 30 ++++++++++++++++++++++++++---- src/transCore.tsx | 13 +++++++++++-- 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/__tests__/useTranslation.test.js b/__tests__/useTranslation.test.js index e2466d5e..0264b6ff 100644 --- a/__tests__/useTranslation.test.js +++ b/__tests__/useTranslation.test.js @@ -1185,7 +1185,7 @@ describe('useTranslation', () => { { count: 3 }, { default: { - example: 'This is a default translation with a count: {{count}}' + example: 'This is a default translation with a count: {{count}}', }, returnObjects: true, fallback: 'ns:no-translation2', @@ -1210,9 +1210,7 @@ describe('useTranslation', () => { 'ns:no-translation', { count: 3 }, { - default: [ - 'This is a default translation with a count: {{count}}' - ], + default: ['This is a default translation with a count: {{count}}'], returnObjects: true, fallback: 'ns:no-translation2', } @@ -1222,6 +1220,30 @@ describe('useTranslation', () => { const expected = 'This is a default translation with a count: 3' + const { container } = render( + + + + ) + expect(container.textContent).toBe(expected) + }) + test('should return falsey default values', () => { + const Inner = () => { + const { t } = useTranslation() + const text = t( + 'ns:no-translation', + { count: 3 }, + { + default: undefined, + returnObjects: true, + fallback: 'ns:no-translation2', + } + ) + return <>{`${text}`} + } + + const expected = 'undefined' + const { container } = render( diff --git a/src/transCore.tsx b/src/transCore.tsx index fc86c3a6..3f5a40aa 100644 --- a/src/transCore.tsx +++ b/src/transCore.tsx @@ -99,8 +99,17 @@ export default function transCore({ } } - if (empty && options?.default && !fallbacks?.length) { - return interpolateUnknown(options.default, query) + if ( + empty && + options && + // options.default could be a nullish value so check that the property exists + options.hasOwnProperty('default') && + !fallbacks?.length + ) { + // if options.default is falsey there's no reason to do interpolation + return options.default + ? interpolateUnknown(options.default, query) + : options.default } // no need to try interpolation