-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLanguageContext.tsx
More file actions
50 lines (42 loc) · 1.43 KB
/
Copy pathLanguageContext.tsx
File metadata and controls
50 lines (42 loc) · 1.43 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
39
40
41
42
43
44
45
46
47
48
49
50
import * as React from 'react';
import { translations } from './translations';
// To avoid potential transpilation issues and make the context more robust,
// we initialize it with a default value that matches the provider's value shape.
const defaultContextValue = {
language: 'en',
setLanguage: (lang) => {}, // Default is a no-op function
t: (key) => translations.en[key] || key, // Default translation function
};
export const LanguageContext = React.createContext(defaultContextValue);
export const LanguageProvider = ({ children }) => {
const [language, setLanguageState] = React.useState(() => {
const savedLang = localStorage.getItem('philfo-lang');
if (savedLang && savedLang in translations) {
return savedLang;
}
return 'en';
});
const setLanguage = (lang) => {
setLanguageState(lang);
localStorage.setItem('philfo-lang', lang);
};
const t = (key) => {
// Fallback to English if the key is missing in the current language
return translations[language]?.[key] || translations.en[key];
};
const value = {
language,
setLanguage,
t,
};
return (
<LanguageContext.Provider value={value}>
{children}
</LanguageContext.Provider>
);
};
export const useLanguage = () => {
// Since we provide a default value to createContext, the context will never be undefined.
// The check for `undefined` is no longer necessary.
return React.useContext(LanguageContext);
};