73 lines
2.2 KiB
TypeScript
73 lines
2.2 KiB
TypeScript
import { useState } from "react";
|
|
import { View, TextInput, Button, Text, Alert, ScrollView } from "react-native";
|
|
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
import { useRouter } from "expo-router";
|
|
import { login, register } from "@/services/auth";
|
|
|
|
export default function AuthScreen() {
|
|
const router = useRouter();
|
|
const [mode, setMode] = useState<"login" | "register">("register");
|
|
|
|
const [email, setEmail] = useState("");
|
|
const [password, setPassword] = useState("");
|
|
|
|
const handleSubmit = async () => {
|
|
if (!email.trim() || !password.trim()) {
|
|
Alert.alert("Lỗi", "Vui lòng nhập email và mật khẩu");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
let res;
|
|
if (mode === "register") {
|
|
res = await register(email, password);
|
|
} else {
|
|
res = await login(email, password);
|
|
}
|
|
|
|
await AsyncStorage.setItem("authToken", res.token);
|
|
router.replace("/(tabs)/home");
|
|
} catch (error) {
|
|
console.log(error);
|
|
Alert.alert("Lỗi", "Sai thông tin đăng nhập hoặc server lỗi");
|
|
}
|
|
};
|
|
|
|
return (
|
|
<ScrollView contentContainerStyle={{ flexGrow: 1, justifyContent: "center", padding: 20 }}>
|
|
<Text style={{ fontSize: 24, fontWeight: "bold", marginBottom: 20 }}>
|
|
{mode === "register" ? "Đăng ký tài khoản" : "Đăng nhập"}
|
|
</Text>
|
|
|
|
<TextInput
|
|
placeholder="Email"
|
|
style={styles.input}
|
|
value={email}
|
|
onChangeText={setEmail}
|
|
keyboardType="email-address"
|
|
autoCapitalize="none"
|
|
/>
|
|
<TextInput
|
|
placeholder="Mật khẩu"
|
|
secureTextEntry
|
|
style={styles.input}
|
|
value={password}
|
|
onChangeText={setPassword}
|
|
/>
|
|
|
|
<Button title={mode === "register" ? "Đăng ký" : "Đăng nhập"} onPress={handleSubmit} />
|
|
|
|
<Text
|
|
style={{ color: "blue", marginTop: 20, textAlign: "center" }}
|
|
onPress={() => setMode(mode === "register" ? "login" : "register")}
|
|
>
|
|
{mode === "register" ? "Đã có tài khoản? Đăng nhập" : "Chưa có tài khoản? Đăng ký"}
|
|
</Text>
|
|
</ScrollView>
|
|
);
|
|
}
|
|
|
|
const styles = {
|
|
input: { borderWidth: 1, marginBottom: 10, padding: 10, borderRadius: 5 },
|
|
};
|