-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
119 lines (105 loc) · 3 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 React, { useState, useEffect } from "react";
import {
SafeAreaView,
ActivityIndicator,
Text,
View,
StatusBar,
} from "react-native";
import Login from "./components/Login";
import AsyncStorage from "@react-native-async-storage/async-storage";
import Toast, { DURATION } from "react-native-easy-toast";
import Navigator from "./components/Navigator";
import { styles } from "./Styles";
export default function App() {
const [isLoggedIn, setIsLoggedIn] = useState(true);
const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState(null);
const [users, setUsers] = useState(null);
useEffect(() => {
async function checkLogin() {
if (await AsyncStorage.getItem("auth-token")) {
const requestOptions = {
method: "GET",
headers: {
Authorization:
"Bearer " + (await AsyncStorage.getItem("auth-token")),
},
};
return fetch(`https://api-v2.exory.dev/user/`, requestOptions)
.then(handleResponse)
.then(async (userResponse) => {
console.trace("Fetched user");
let user = userResponse;
setUser(user);
setIsLoggedIn(true);
if (user.admin === true) {
getUsers();
}
// return user;
})
.catch((error) => {
console.log(error);
setIsLoggedIn(false);
});
} else {
setIsLoggedIn(false);
}
}
checkLogin();
}, [isLoggedIn]);
let getUsers = async () => {
const requestOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + (await AsyncStorage.getItem("auth-token")),
},
};
return fetch(`https://api-v2.exory.dev/user/all`, requestOptions)
.then(handleResponse)
.then(async (userResponse) => {
let usersArray = [];
//console.log(userResponse);
userResponse.forEach((user) => {
user.avatar.url = user.avatar.url.replace(".svg", ".png");
usersArray.push(user);
});
setUsers(usersArray);
return true;
})
.catch((error) => {
setErrMsg(error);
console.log(error);
return false;
});
};
// handle response != 200 and display message
let handleResponse = (response) => {
return response.json().then((text) => {
if (!response.ok) {
if (response.status === 401) {
}
const error = text || response.statusText;
return Promise.reject(error);
}
return text;
});
};
return (
<View style={styles.view}>
<Toast ref={(toast) => (this.toast = toast)} />
{isLoggedIn ? (
<Navigator
setIsLoggedIn={setIsLoggedIn}
user={user}
users={users}
getUsers={getUsers}
setUsers={setUsers}
/>
) : (
<Login isLoggedIn={isLoggedIn} setIsLoggedIn={setIsLoggedIn} />
)}
</View>
);
}