refactor(i18n): Improve context value handling in I18nProvider
This commit is contained in:
parent
7a2e3eb862
commit
4ca5c59ffe
1 changed files with 15 additions and 12 deletions
|
|
@ -11,33 +11,36 @@ import type { LangDict, Locales } from "~/i18n/locales";
|
|||
|
||||
type I18nContextType = {
|
||||
locale: Locales;
|
||||
t: LangDict;
|
||||
};
|
||||
|
||||
const I18nContext = createContext<I18nContextType>({
|
||||
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 (
|
||||
<I18nContext.Provider value={{ locale: validateLocale(locale) }}>
|
||||
{children}
|
||||
</I18nContext.Provider>
|
||||
<I18nContext.Provider value={contextValue}>{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 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";
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue