-
Notifications
You must be signed in to change notification settings - Fork 10
/
App.js
119 lines (108 loc) · 3.16 KB
/
App.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import { useEffect, useMemo, useReducer } from "react";
import { Alert } from "react-native";
import { Onboarding } from "./screens/Onboarding";
import { Profile } from "./screens/Profile";
import SplashScreen from "./screens/SplashScreen";
import { Home } from "./screens/Home";
import { StatusBar } from "expo-status-bar";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { AuthContext } from "./contexts/AuthContext";
const Stack = createNativeStackNavigator();
export default function App({ navigation }) {
const [state, dispatch] = useReducer(
(prevState, action) => {
switch (action.type) {
case "onboard":
return {
...prevState,
isLoading: false,
isOnboardingCompleted: action.isOnboardingCompleted,
};
}
},
{
isLoading: true,
isOnboardingCompleted: false,
}
);
useEffect(() => {
(async () => {
let profileData = [];
try {
const getProfile = await AsyncStorage.getItem("profile");
if (getProfile !== null) {
profileData = getProfile;
}
} catch (e) {
console.error(e);
} finally {
if (Object.keys(profileData).length != 0) {
dispatch({ type: "onboard", isOnboardingCompleted: true });
} else {
dispatch({ type: "onboard", isOnboardingCompleted: false });
}
}
})();
}, []);
const authContext = useMemo(
() => ({
onboard: async (data) => {
try {
const jsonValue = JSON.stringify(data);
await AsyncStorage.setItem("profile", jsonValue);
} catch (e) {
console.error(e);
}
dispatch({ type: "onboard", isOnboardingCompleted: true });
},
update: async (data) => {
try {
const jsonValue = JSON.stringify(data);
await AsyncStorage.setItem("profile", jsonValue);
} catch (e) {
console.error(e);
}
Alert.alert("Success", "Successfully saved changes!");
},
logout: async () => {
try {
await AsyncStorage.clear();
} catch (e) {
console.error(e);
}
dispatch({ type: "onboard", isOnboardingCompleted: false });
},
}),
[]
);
if (state.isLoading) {
return <SplashScreen />;
}
return (
<AuthContext.Provider value={authContext}>
<StatusBar style="dark" />
<NavigationContainer>
<Stack.Navigator>
{state.isOnboardingCompleted ? (
<>
<Stack.Screen
name="Home"
component={Home}
options={{ headerShown: false }}
/>
<Stack.Screen name="Profile" component={Profile} />
</>
) : (
<Stack.Screen
name="Onboarding"
component={Onboarding}
options={{ headerShown: false }}
/>
)}
</Stack.Navigator>
</NavigationContainer>
</AuthContext.Provider>
);
}