Skip to content

Commit

Permalink
Allow for falsey default values (#1021)
Browse files Browse the repository at this point in the history
Co-authored-by: zsunderland <[email protected]>
  • Loading branch information
SimplyComplexable and zsunderland authored Apr 11, 2023
1 parent 4898199 commit ab6b93b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
30 changes: 26 additions & 4 deletions __tests__/useTranslation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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',
}
Expand All @@ -1222,6 +1220,30 @@ describe('useTranslation', () => {

const expected = 'This is a default translation with a count: 3'

const { container } = render(
<I18nProvider lang="en" namespaces={{}}>
<Inner />
</I18nProvider>
)
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(
<I18nProvider lang="en" namespaces={{}}>
<Inner />
Expand Down
13 changes: 11 additions & 2 deletions src/transCore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit ab6b93b

Please sign in to comment.