-
Notifications
You must be signed in to change notification settings - Fork 0
/
Loader.js
80 lines (70 loc) · 2.03 KB
/
Loader.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import React, { useState, createContext, useEffect } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { ToastAndroid } from "react-native";
export const LoaderContext = createContext();
const defaultSettings = {
others: {
theme: "dark",
},
};
// TODO: replace app-name wiht actual app name
const KEY = "@app-name_settings";
const FIRST_TIME_KEY = "@app-name_firsttime";
export const LoaderProvider = (props) => {
const [loading, setLoading] = useState(true);
const [settings, setSettings] = useState(null);
const [firsttime, setFirsttime] = useState(false);
useEffect(() => {
getSettings().then((settings) => {
setSettings(settings);
setLoading(false);
});
}, []);
const getSettings = async () => {
try {
const jsonValue = await AsyncStorage.multiGet([KEY, FIRST_TIME_KEY]);
if (!jsonValue[1][1]) {
setFirsttime(true);
}
if (!jsonValue[0][1]) {
await AsyncStorage.setItem(KEY, JSON.stringify(defaultSettings));
return defaultSettings;
}
return JSON.parse(jsonValue[0][1]);
} catch (error) {
console.log("Settings Context Loading => " + error);
return defaultSettings;
}
};
const setNewSettings = async (newSettings) => {
await AsyncStorage.setItem(KEY, JSON.stringify(newSettings));
setSettings(newSettings);
if (newSettings === defaultSettings) {
ToastAndroid.show("Default settings applied", ToastAndroid.LONG);
} else {
ToastAndroid.show("Settings applied", ToastAndroid.LONG);
}
};
const resetSettings = async () => {
setNewSettings(defaultSettings);
};
const removeFirsttime = async () => {
await AsyncStorage.setItem(FIRST_TIME_KEY, "true");
setFirsttime(false);
return true;
};
return (
<LoaderContext.Provider
value={{
loading,
settings,
setNewSettings,
resetSettings,
firsttime,
removeFirsttime,
}}
>
{props.children}
</LoaderContext.Provider>
);
};