Untitled
unknown
plain_text
3 years ago
3.4 kB
7
Indexable
import React, { useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { View, TextInput, Button, Text, StyleSheet } from 'react-native';
import LoginPage from './LoginPage';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 16,
},
inputContainer: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 10,
width: '100%',
},
label: {
marginRight: 10,
fontWeight: 'bold',
width: 120,
},
input: {
flex: 1,
borderWidth: 1,
padding: 10,
},
button: {
width: '100%',
marginTop: 10,
},
buttonText: {
color: 'white',
textAlign: 'center',
},
welcomeText: {
marginBottom: 10,
fontSize: 18,
fontWeight: 'bold',
},
});
const LoginScreen = ({ onLogin }) => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleLogin = async () => {
try {
const storedUsers = JSON.parse(await AsyncStorage.getItem('users')) || [];
const existingUser = storedUsers.find(user => user.username === username);
if (existingUser) {
// User exists, check if the password is correct
if (existingUser.password === password) {
onLogin(existingUser.username); // Pass the username to onLogin
} else {
alert('Incorrect password');
}
} else {
// User does not exist, store the username and password
const newUser = { username, password };
storedUsers.push(newUser);
await AsyncStorage.setItem('users', JSON.stringify(storedUsers));
onLogin(newUser.username); // Pass the username to onLogin
}
} catch (error) {
console.error('Error occurred during login:', error);
alert('Login failed');
}
};
return (
<View style={styles.container}>
<View style={styles.inputContainer}>
<Text style={styles.label}> USERNAME:</Text>
<TextInput
placeholder="Username"
value={username}
onChangeText={setUsername}
style={styles.input}
/>
</View>
<View style={styles.inputContainer}>
<Text style={styles.label}> Password:</Text>
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
style={styles.input}
/>
</View>
<Button title="Login" onPress={handleLogin} style={styles.button} color="blue" />
</View>
);
};
const App = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [username, setUsername] = useState('');
const [leaveReason, setLeaveReason] = useState('');
const handleLogin = (username) => {
setIsLoggedIn(true);
setUsername(username);
};
const handleLogout = () => {
setIsLoggedIn(false);
setUsername('');
setLeaveReason('');
};
const handleEnterLeaveReason = (reason) => {
setLeaveReason(reason);
};
return (
<View style={styles.container}>
{isLoggedIn ? (
<LoginPage
onLogout={handleLogout}
username={username}
onEnterLeaveReason={handleEnterLeaveReason}
/>
) : (
<LoginScreen onLogin={handleLogin} />
)}
</View>
);
};
export default App;
Editor is loading...