mediahub-fe/hooks/use-translation-with-defaul...

24 lines
878 B
TypeScript

import { useTranslations } from "next-intl";
/**
* Custom hook that provides translation function with default values
* This ensures that when translations are not ready, a default value is shown
* Format: t("key", { defaultValue: "Default Value" })
*/
export function useTranslationWithDefaults(namespace: string) {
const t = useTranslations(namespace);
return (key: string, options?: { defaultValue?: string }) => {
try {
const translation = t(key);
// If translation returns the same key (fallback behavior), use default value
if (translation === key && options?.defaultValue) {
return options.defaultValue;
}
return translation || options?.defaultValue || key;
} catch (error) {
// If translation fails (e.g., key not found), return default value or key
return options?.defaultValue || key;
}
};
}