All files / src/hooks useFallbackTranslation.ts

100% Statements 15/15
87.5% Branches 7/8
100% Functions 3/3
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 231x 1x 1x       1x   1x 1336x 1336x   1336x 1336x   1336x 259x 259x 259x   1336x 1336x  
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';
 
type TranslationFunction = (key: string, options?: any) => string;
 
const getNamespaceFromPath = (pathname: string): string | null => (pathname === '/' ? 'main' : null);
 
export const useFallbackTranslation = (): { t: TranslationFunction } => {
  const location = useLocation();
  const primaryNs = useMemo(() => getNamespaceFromPath(location.pathname), [location.pathname]);
 
  const { t: tFallback } = useTranslation('common');
  const { t: tPrimary } = useTranslation(primaryNs ?? 'common');
 
  const t: TranslationFunction = (key, options) => {
    const result = tPrimary(key, options);
    return result === key ? tFallback(key, options).toString() : result.toString();
  };
 
  return { t };
};