fuse_expo/components/UserSelection.tsx

118 lines
2.7 KiB
TypeScript
Raw Normal View History

2024-09-10 00:59:55 -05:00
import React, { useState, useEffect } from 'react';
import { TouchableOpacity, StyleSheet, ActivityIndicator } from 'react-native';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
2024-09-10 16:57:14 -05:00
import { LinearGradient } from 'expo-linear-gradient';
2024-09-10 00:59:55 -05:00
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';
interface User {
id: number;
name: string;
message: string;
}
interface UserSelectionProps {
onUserSelected: (user: User) => void;
}
2024-09-10 13:30:33 -05:00
const API_KEY = process.env.EXPO_PUBLIC_API_KEY;
const BASE_URL = process.env.EXPO_PUBLIC_BASE_URL;
2024-09-10 00:59:55 -05:00
const UserSelection: React.FC<UserSelectionProps> = ({ onUserSelected }) => {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
checkStoredUser();
}, []);
const checkStoredUser = async () => {
try {
const storedUser = await AsyncStorage.getItem('@user');
if (storedUser) {
onUserSelected(JSON.parse(storedUser));
} else {
fetchUsers();
}
} catch (e) {
console.error('Failed to load user', e);
fetchUsers();
}
};
const fetchUsers = async () => {
try {
const response = await axios.get(`${BASE_URL}/getUsers`, {
params: { apiKey: API_KEY }
});
setUsers(response.data);
} catch (e) {
console.error('Failed to fetch users', e);
} finally {
setLoading(false);
}
};
const selectUser = async (user: User) => {
try {
await AsyncStorage.setItem('@user', JSON.stringify(user));
onUserSelected(user);
} catch (e) {
console.error('Failed to save user', e);
}
};
if (loading) {
return (
<ThemedView style={styles.container}>
<ActivityIndicator size="large" color="#0000ff" />
</ThemedView>
);
}
return (
<ThemedView style={styles.container}>
<ThemedText style={styles.title}>Who are you?</ThemedText>
{users.map((user) => (
<TouchableOpacity
key={user.id}
style={styles.button}
onPress={() => selectUser(user)}
>
<ThemedText style={styles.buttonText}>{user.name}</ThemedText>
</TouchableOpacity>
))}
</ThemedView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
title: {
2024-09-10 16:57:14 -05:00
fontSize: 48,
lineHeight: 56,
2024-09-10 00:59:55 -05:00
fontWeight: 'bold',
marginBottom: 20,
},
button: {
2024-09-10 16:57:14 -05:00
backgroundColor: '#730FF8',
2024-09-10 00:59:55 -05:00
padding: 15,
borderRadius: 5,
marginVertical: 10,
width: 200,
alignItems: 'center',
},
buttonText: {
color: 'white',
2024-09-10 16:57:14 -05:00
fontSize: 24,
2024-09-10 00:59:55 -05:00
fontWeight: 'bold',
},
});
export default UserSelection;