Migrate to vite & new structure
Signed-off-by: Bryan Frimin <bryan@getprobo.com> Signed-off-by: Sacha Al Himdani <sacha@getprobo.com>
This commit is contained in:
committed by
Sacha Al Himdani
parent
db9e5f32ac
commit
a2d1310780
60
packages/i18n/TranslatorProvider.tsx
Normal file
60
packages/i18n/TranslatorProvider.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
import {
|
||||
createContext,
|
||||
PropsWithChildren,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
const defaultValue = {
|
||||
lang: "en" as "en" | "fr",
|
||||
translations: {} as Record<string, string>,
|
||||
translate: (s: string) => s,
|
||||
};
|
||||
|
||||
type Context = typeof defaultValue;
|
||||
|
||||
const TranslatorContext = createContext(defaultValue);
|
||||
|
||||
type Props = {
|
||||
lang: "en" | "fr";
|
||||
loader: (lang: string) => Promise<Record<string, string>>;
|
||||
};
|
||||
|
||||
export function TranslatorProvider({
|
||||
lang,
|
||||
loader,
|
||||
children,
|
||||
}: PropsWithChildren<Props>) {
|
||||
const [translations, setTranslations] = useState(
|
||||
{} as Record<string, string>,
|
||||
);
|
||||
const translate = useCallback<Context["translate"]>(
|
||||
(s) => {
|
||||
return translations[s] ? translations[s] : s;
|
||||
},
|
||||
[translations],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
loader(lang).then(setTranslations);
|
||||
}, [lang]);
|
||||
|
||||
return (
|
||||
<TranslatorContext.Provider
|
||||
value={{ lang, translations, translate }}
|
||||
>
|
||||
{children}
|
||||
</TranslatorContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useTranslate() {
|
||||
const { translate, lang } =
|
||||
useContext(TranslatorContext);
|
||||
return {
|
||||
lang,
|
||||
__: translate,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user