-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLanguageContext.tsx
More file actions
38 lines (31 loc) · 1.14 KB
/
LanguageContext.tsx
File metadata and controls
38 lines (31 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* eslint-disable react-refresh/only-export-components */
import React, { createContext, useContext, useState } from 'react';
import { translations, type Language } from '../i18n';
interface LanguageContextType {
lang: Language;
setLang: (lang: Language) => void;
t: (key: keyof typeof translations['RU']) => string;
}
const LanguageContext = createContext<LanguageContextType | undefined>(undefined);
export function LanguageProvider({ children }: { children: React.ReactNode }) {
const [lang, setLangState] = useState<Language>(() => {
return (localStorage.getItem('dubtab_lang') as Language) || 'RU';
});
const setLang = (newLang: Language) => {
localStorage.setItem('dubtab_lang', newLang);
setLangState(newLang);
};
const t = (key: keyof typeof translations['RU']) => {
return translations[lang][key] || key;
};
return (
<LanguageContext.Provider value={{ lang, setLang, t }}>
{children}
</LanguageContext.Provider>
);
}
export function useLanguage() {
const context = useContext(LanguageContext);
if (!context) throw new Error('useLanguage must be used within LanguageProvider');
return context;
}