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 = {
|
type I18nContextType = {
|
||||||
locale: Locales;
|
locale: Locales;
|
||||||
|
t: LangDict;
|
||||||
};
|
};
|
||||||
|
|
||||||
const I18nContext = createContext<I18nContextType>({
|
const I18nContext = createContext<I18nContextType>({
|
||||||
locale: "it",
|
locale: "it",
|
||||||
|
t: it,
|
||||||
});
|
});
|
||||||
|
|
||||||
export const I18nProvider: FC<{
|
export const I18nProvider: FC<{
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
locale: string | undefined;
|
locale: string | undefined;
|
||||||
}> = ({ children, locale }) => {
|
}> = ({ children, locale }) => {
|
||||||
|
const contextValue = useMemo(() => {
|
||||||
|
const validatedLocale = validateLocale(locale);
|
||||||
|
return {
|
||||||
|
locale: validatedLocale,
|
||||||
|
t: validatedLocale === "en" ? en : it,
|
||||||
|
};
|
||||||
|
}, [locale]);
|
||||||
return (
|
return (
|
||||||
<I18nContext.Provider value={{ locale: validateLocale(locale) }}>
|
<I18nContext.Provider value={contextValue}>{children}</I18nContext.Provider>
|
||||||
{children}
|
|
||||||
</I18nContext.Provider>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useTranslation = () => {
|
export const useTranslation = () => {
|
||||||
const { locale } = useContext(I18nContext);
|
const value = useContext(I18nContext);
|
||||||
return useMemo(() => {
|
if (!value) {
|
||||||
return (
|
throw new Error("useTranslation must be used within a I18nProvider");
|
||||||
locale === "en" ? { locale: "en", t: en } : { locale: "it", t: it }
|
}
|
||||||
) as {
|
return value;
|
||||||
locale: Locales;
|
|
||||||
t: LangDict;
|
|
||||||
};
|
|
||||||
}, [locale]);
|
|
||||||
};
|
};
|
||||||
const validateLocale = (locale: string | undefined): Locales => {
|
const validateLocale = (locale: string | undefined): Locales => {
|
||||||
if (locale === "en") return "en";
|
if (locale === "en") return "en";
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue