railbird-gql/screens/login.tsx

107 lines
2.7 KiB
TypeScript
Raw Normal View History

// Login.tsx
2024-02-06 12:34:52 -07:00
import AsyncStorage from "@react-native-async-storage/async-storage";
import { FirebaseAuthTypes } from "@react-native-firebase/auth";
import React, { useEffect, useState } from "react";
2024-02-01 19:43:44 -07:00
import {
Button,
2024-02-03 20:30:00 -07:00
Keyboard,
Text,
TextInput,
TouchableWithoutFeedback,
2024-02-03 20:30:00 -07:00
View,
2024-02-06 12:34:52 -07:00
} from "react-native";
import {
confirmCode,
handleSignInWithPhoneNumber,
onAuthStateChanged,
} from "../auth";
import SignOutButton from "../component/buttons/sign-out";
import { useAuthHeader } from "../graphql/client";
2024-02-01 19:43:44 -07:00
export default function Login({ navigation }) {
2024-02-06 12:34:52 -07:00
const [phoneNumber, setPhoneNumber] = useState<string>("");
const [code, setCode] = useState<string>("");
const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null);
2024-02-06 12:34:52 -07:00
const [confirm, setConfirm] =
useState<FirebaseAuthTypes.ConfirmationResult | null>(null);
const { authHeader, setAuthHeader } = useAuthHeader();
useEffect(() => {
const unsubscribe = onAuthStateChanged(async (user) => {
2024-02-06 12:34:52 -07:00
setUser(user);
if (user) {
2024-02-06 12:34:52 -07:00
const token = await user.getIdToken();
if (token) {
2024-02-06 12:34:52 -07:00
await AsyncStorage.setItem("token", token);
setAuthHeader({ key: "Authorization", value: token });
}
}
});
return unsubscribe;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
console.log(authHeader.value)
return (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
2024-02-06 12:34:52 -07:00
<View style={{ alignItems: "center" }}>
<TextInput
style={{
width: "50%",
height: 30,
borderWidth: 1,
borderColor: "black",
marginBottom: 20,
}}
placeholder="Phone"
textContentType="telephoneNumber"
keyboardType="phone-pad"
autoCapitalize="none"
value={phoneNumber}
onChangeText={(value) => setPhoneNumber(value)}
/>
{confirm && (
<TextInput
style={{
width: "50%",
height: 30,
borderWidth: 1,
borderColor: "black",
marginBottom: 20,
}}
placeholder="Code"
keyboardType="number-pad"
textContentType="oneTimeCode"
autoCapitalize="none"
value={code}
onChangeText={(value) => setCode(value)}
/>
)}
<Button
2024-02-06 12:34:52 -07:00
title={!confirm ? "Receive code" : "Confirm code"}
onPress={() =>
!confirm
? handleSignInWithPhoneNumber(phoneNumber).then(setConfirm)
: confirm && confirmCode(confirm, code)
}
/>
2024-02-06 12:34:52 -07:00
<Text>
{authHeader.key}: {authHeader.value}
</Text>
{user && (
<>
<Text style={{ marginTop: 10 }}>
Display name: {user?.displayName}
</Text>
<Text>Phone number: {user?.phoneNumber}</Text>
<SignOutButton />
<Button color="orange" title="Go to app" onPress={() => navigation.push("Tabs")} />
</>
)}
</View>
</TouchableWithoutFeedback>
);
2024-02-01 19:43:44 -07:00
}