Skip to content

Commit

Permalink
if defaultValue is passed in not ready t functio (via useTranslation)…
Browse files Browse the repository at this point in the history
… return that instead of the key, even though the user-land could should be fixed #1618
  • Loading branch information
adrai committed Feb 23, 2023
1 parent 7f76aa9 commit a03b69b
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
### 12.2.0

- if defaultValue is passed in not ready t functio (via useTranslation) return that instead of the key, even though the user-land could should be fixed [1618](https://github.com/i18next/react-i18next/issues/1618)

### 12.1.5

- fix react merged types [1606](https://github.com/i18next/react-i18next/pull/1606) originally introduced with #1531 to address #1506
Expand Down
11 changes: 10 additions & 1 deletion src/useTranslation.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,16 @@ export function useTranslation(ns, props = {}) {
if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();
if (!i18n) {
warnOnce('You will need to pass in an i18next instance by using initReactI18next');
const notReadyT = (k) => (Array.isArray(k) ? k[k.length - 1] : k);
const notReadyT = (k, optsOrDefaultValue) => {
if (typeof optsOrDefaultValue === 'string') return optsOrDefaultValue;
if (
optsOrDefaultValue &&
typeof optsOrDefaultValue === 'object' &&
typeof optsOrDefaultValue.defaultValue === 'string'
)
return optsOrDefaultValue.defaultValue;
return Array.isArray(k) ? k[k.length - 1] : k;
};
const retNotReady = [notReadyT, {}, false];
retNotReady.t = notReadyT;
retNotReady.i18n = {};
Expand Down
9 changes: 9 additions & 0 deletions test/useTranslation.loading.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,13 @@ describe('useTranslation loading ns', () => {
await waitForNextUpdate();
expect(t('key1')).toBe('test');
});

it('should return defaultValue if i18n instance not found', async () => {
const { result } = renderHook(() =>
useTranslation('common', { i18n: newI18n, useSuspense: false }),
);
const { t } = result.current;
expect(t('key1', 'my default value')).toBe('my default value');
expect(t('key1', { defaultValue: 'my default value' })).toBe('my default value');
});
});

0 comments on commit a03b69b

Please sign in to comment.