-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSettingsProvider.js
More file actions
52 lines (40 loc) · 1.67 KB
/
SettingsProvider.js
File metadata and controls
52 lines (40 loc) · 1.67 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
51
52
import { useState, createContext, useContext } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Localization from 'expo-localization';
import { themes } from './constants/themes';
import { translations } from './constants/translations';
const SettingsContext = createContext();
export default function SettingsProvider({ children }) {
const defaultSettings = {
language: Localization.getLocales()[0].languageCode,
theme: 'dark',
defaultUsername: null
}
const [settings, setSettings] = useState(defaultSettings);
const loadSettings = async () => {
const savedSettings = await AsyncStorage.getItem('settings');
if (!savedSettings) setSettings(defaultSettings);
else setSettings(JSON.parse(savedSettings));
}
const updateSettings = async (newSettings) => {
const updatedSettings = { ...settings, ...newSettings };
setSettings(updatedSettings);
try {
await AsyncStorage.setItem('settings', JSON.stringify(updatedSettings));
} catch (error) {
console.error(error);
}
}
const restoreDefault = async () => {
await AsyncStorage.removeItem('settings');
setSettings(defaultSettings);
}
const translate = (key) => translations[settings.language][key] || key;
const getColor = (key) => themes[settings.theme][key] || key;
return (
<SettingsContext.Provider value={{ settings, getColor, loadSettings, restoreDefault, translate, updateSettings }}>
{children}
</SettingsContext.Provider>
)
}
export const useSettings = () => useContext(SettingsContext);