Skip to content

Commit

Permalink
✨ Fallback on missing translations [#16]
Browse files Browse the repository at this point in the history
  • Loading branch information
DRFR0ST authored Feb 7, 2023
2 parents 3ff8600 + bf9c02b commit 7fcbf1b
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export function useLittera<T extends ITranslations<T>>(t: TTranslationsArg<T, IT
const locales = context.locales ?? [locale];

const translations = React.useMemo(() => isTransFn<T, ITranslationsPreset<typeof preset>>(t) ? { ...t(preset) } : { ...t }, [t, preset]) as T;

React.useEffect(() => {
reportMissing(translations, locales)
}, [translations]);
Expand Down
4 changes: 3 additions & 1 deletion src/utils/translate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,5 +98,7 @@ export function translateSingle<T>(translation: T, locale: string) {
if (isVariableFunction(translation))
return ((...args: Parameters<typeof translation>) => translation(...args)[locale]) as ISingleTranslated<T>;

return translation[locale] as ISingleTranslated<T>;
const defaultLocale = Object.keys(translation)[0];

return (translation[locale] || translation[defaultLocale]) as ISingleTranslated<T>;
}
10 changes: 10 additions & 0 deletions tests/hooks.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,16 @@ describe("useLittera", () => {
// @ts-ignore
expect(console.warn.mock.calls[0][0]).toBe(`You are missing "simple" in de_DE.`);
});

it("should fall back to available locale if translations for active are missing", () => {
console.warn = jest.fn();
const render = renderHook(() => useLittera(mockMissingTranslations, "de_DE"), { wrapper });
const translated = render.result.current;

const fallbackLocale = Object.keys(mockMissingTranslations.simple)[0];

expect(translated.simple).toEqual(mockMissingTranslations.simple[fallbackLocale]);
});
});

describe("useLitteraMethods", () => {
Expand Down

0 comments on commit 7fcbf1b

Please sign in to comment.