From 4ca5c59ffeffcf044d61e056bf2f90f4b90e5c6b Mon Sep 17 00:00:00 2001 From: Marco Pedone Date: Mon, 3 Nov 2025 16:02:27 +0100 Subject: [PATCH] refactor(i18n): Improve context value handling in I18nProvider --- .../src/providers/I18nProvider.tsx | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/apps/infoalloggi/src/providers/I18nProvider.tsx b/apps/infoalloggi/src/providers/I18nProvider.tsx index 93edf52..0588925 100644 --- a/apps/infoalloggi/src/providers/I18nProvider.tsx +++ b/apps/infoalloggi/src/providers/I18nProvider.tsx @@ -11,33 +11,36 @@ import type { LangDict, Locales } from "~/i18n/locales"; type I18nContextType = { locale: Locales; + t: LangDict; }; const I18nContext = createContext({ locale: "it", + t: it, }); export const I18nProvider: FC<{ children: ReactNode; locale: string | undefined; }> = ({ children, locale }) => { + const contextValue = useMemo(() => { + const validatedLocale = validateLocale(locale); + return { + locale: validatedLocale, + t: validatedLocale === "en" ? en : it, + }; + }, [locale]); return ( - - {children} - + {children} ); }; 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 value = useContext(I18nContext); + if (!value) { + throw new Error("useTranslation must be used within a I18nProvider"); + } + return value; }; const validateLocale = (locale: string | undefined): Locales => { if (locale === "en") return "en";