# All files / src/lib I18nContext.tsx

90% Statements 9/10
100% Branches 0/0
66.66% Functions 4/6
90% Lines 9/10

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
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38

    1x

    6x

    6x
    2x
    2x

    6x
    6x

    6x

    6x

     import { createContext, useContext, useState, useCallback, type ReactNode } from 'react';
    import { type UILocale, getUILocale, setUILocale as persistLocale, t } from './i18n';

    interface I18nContextValue {
      locale: UILocale;
      setLocale: (l: UILocale) => void;
      t: (key: string, ...args: (string | number)[]) => string;
    }

    const I18nContext = createContext<I18nContextValue>({
      locale: 'fr',
      setLocale: () => {},
      t: (key) => key,
    });

    export function I18nProvider({ children }: { children: ReactNode }) {
      const [locale, setLocaleState] = useState<UILocale>(getUILocale);

      const setLocale = useCallback((l: UILocale) => {
        persistLocale(l);
        setLocaleState(l);
      }, []);

      const translate = useCallback((key: string, ...args: (string | number)[]) => {
        return t(locale, key, ...args);
      }, [locale]);

      return (
        <I18nContext.Provider value={{ locale, setLocale, t: translate }}>
          {children}
        </I18nContext.Provider>
      );
    }

    export function useT() {
      return useContext(I18nContext);
    }