infoalloggi-monorepo/apps/infoalloggi/src/providers/I18nProvider.tsx

46 lines
988 B
TypeScript
Raw Normal View History

2025-08-04 17:45:44 +02:00
import type { LangDict, Locales } from "~/i18n/locales";
import { en } from "~/i18n/en";
import { it } from "~/i18n/it";
import {
createContext,
useContext,
useMemo,
type FC,
type ReactNode,
} from "react";
type I18nContextType = {
locale: Locales;
};
const I18nContext = createContext<I18nContextType>({
locale: "it",
});
export const I18nProvider: FC<{
children: ReactNode;
locale: string | undefined;
}> = ({ children, locale }) => {
return (
<I18nContext.Provider value={{ locale: validateLocale(locale) }}>
{children}
</I18nContext.Provider>
);
};
export const useTranslation = () => {
const { locale } = useContext(I18nContext);
return useMemo(() => {
return (
locale === "en" ? { locale: "en", t: en } : { locale: "it", t: it }
) as {
locale: Locales;
t: LangDict;
};
}, [locale]);
};
const validateLocale = (locale: string | undefined): Locales => {
if (locale === "en") return "en";
return "it";
};