(react) expose currentLocale in CunninghamContext

Expose `currentLocale` value to let know its subscribers
what is the locale value currently in use.
This commit is contained in:
Lebaud Antoine
2023-06-26 18:55:13 +02:00
committed by aleb_the_flash
parent 3b13bcae65
commit f03ef6a9e1
2 changed files with 56 additions and 6 deletions

View File

@@ -15,6 +15,7 @@ const CunninghamContext = createContext<
| undefined
| {
t: (key: string, vars?: Record<string, string | number>) => string;
currentLocale: string;
}
>(undefined);
@@ -57,17 +58,14 @@ export const CunninghamProvider = ({
);
const locale = useMemo(() => {
if (!locales[currentLocale]) {
return locales[DEFAULT_LOCALE];
}
return locales[currentLocale];
return (locales[currentLocale] && currentLocale) || DEFAULT_LOCALE;
}, [currentLocale, locales]);
const context = useMemo(
() => ({
t: (key: string, vars?: Record<string, string | number>) => {
let message: string =
findTranslation(key, locale) ??
findTranslation(key, locales[locale]) ??
findTranslation(key, locales[DEFAULT_LOCALE]) ??
key;
@@ -80,6 +78,7 @@ export const CunninghamProvider = ({
return message;
},
currentLocale: locale,
}),
[currentLocale, locales]
);