import { useLocalStorage } from "@hooks/useStorage"; import * as translations from "./translations"; type TranslationFunction = (key: string) => string | undefined; export default function useTranslation(lang: string, fallbackLang: string) { const [language, setLanguage] = useLocalStorage("language", lang); const [fallbackLanguage, setFallbackLanguage] = useLocalStorage( "fallbackLanguage", fallbackLang ); const translate: TranslationFunction = (key) => { const keys = key.split("."); return ( getNestedTranslation(language, keys) ?? getNestedTranslation(fallbackLanguage, keys) ?? key ); }; return { language, setLanguage, fallbackLanguage, setFallbackLanguage, t: translate, }; } function getNestedTranslation( language: string, keys: string[] ): string | undefined { return keys.reduce((obj, key) => { return obj?.[key]; }, translations[language]); }