forked from betomoedano/React-Navigation-App-Example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
68 lines (62 loc) · 2.03 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
import "react-native-gesture-handler";
import * as React from "react";
import Navigation from "./Navigation";
import * as WebBrowser from "expo-web-browser";
import * as Google from "expo-auth-session/providers/google";
import {
GoogleAuthProvider,
onAuthStateChanged,
signInWithCredential,
} from "firebase/auth";
import { auth } from "./firebaseConfig";
import SignInScreen from "./screens/SignInScreen";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { ActivityIndicator, View } from "react-native";
WebBrowser.maybeCompleteAuthSession();
export default function App() {
const [userInfo, setUserInfo] = React.useState();
const [loading, setLoading] = React.useState(false);
const [request, response, promptAsync] = Google.useAuthRequest({
iosClientId: "",
androidClientId: "",
});
const getLocalUser = async () => {
try {
setLoading(true);
const userJSON = await AsyncStorage.getItem("@user");
const userData = userJSON ? JSON.parse(userJSON) : null;
setUserInfo(userData);
} catch (e) {
console.log(e, "Error getting local user");
} finally {
setLoading(false);
}
};
React.useEffect(() => {
if (response?.type === "success") {
const { id_token } = response.params;
const credential = GoogleAuthProvider.credential(id_token);
signInWithCredential(auth, credential);
}
}, [response]);
React.useEffect(() => {
getLocalUser();
const unsub = onAuthStateChanged(auth, async (user) => {
if (user) {
await AsyncStorage.setItem("@user", JSON.stringify(user));
console.log(JSON.stringify(user, null, 2));
setUserInfo(user);
} else {
console.log("user not authenticated");
}
});
return () => unsub();
}, []);
if (loading)
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<ActivityIndicator size={"large"} />
</View>
);
return userInfo ? <Navigation /> : <SignInScreen promptAsync={promptAsync} />;
}