fuse_expo/app/(tabs)/sendmessage.tsx

126 lines
3.1 KiB
TypeScript

import React, { useState, useEffect } from 'react';
import {
StyleSheet,
TextInput,
TouchableOpacity,
Alert,
Keyboard,
TouchableWithoutFeedback,
KeyboardAvoidingView,
Platform
} from 'react-native';
import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';
const API_KEY = process.env.EXPO_PUBLIC_API_KEY;
const BASE_URL = process.env.EXPO_PUBLIC_BASE_URL;
export default function SendMessageScreen() {
const [message, setMessage] = useState('');
const [userId, setUserId] = useState(null);
useEffect(() => {
getUserId();
}, []);
const getUserId = async () => {
try {
const storedUser = await AsyncStorage.getItem('@user');
if (storedUser) {
const user = JSON.parse(storedUser);
setUserId(user.id);
}
} catch (error) {
console.error('Failed to get user ID:', error);
}
};
const sendMessage = async () => {
if (!message.trim()) {
Alert.alert('Error', 'Please enter a message');
return;
}
if (!userId) {
Alert.alert('Error', 'User not found. Please select a user first.');
return;
}
try {
await axios.post(`${BASE_URL}/setMessage`, null, {
params: { apiKey: API_KEY, userId, message }
});
Alert.alert('Success', 'Message sent successfully');
setMessage('');
Keyboard.dismiss();
} catch (error) {
console.error('Failed to send message:', error);
Alert.alert('Error', 'Failed to send message. Please try again.');
}
};
return (
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={{flex: 1}}
>
<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
<ThemedView style={styles.container}>
<ThemedText style={styles.title}>Send a Message</ThemedText>
<TextInput
style={styles.input}
value={message}
onChangeText={setMessage}
placeholder="Enter your message"
placeholderTextColor="#999"
multiline
/>
<TouchableOpacity style={styles.button} onPress={sendMessage}>
<ThemedText style={styles.buttonText}>Send Message</ThemedText>
</TouchableOpacity>
</ThemedView>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
padding: 20,
},
title: {
fontSize: 36,
lineHeight: 40,
fontWeight: 'bold',
marginBottom: 20,
textAlign: 'center',
},
input: {
width: '100%',
height: 80,
borderColor: '#ccc',
borderWidth: 1,
borderRadius: 5,
padding: 10,
marginBottom: 20,
textAlignVertical: 'top',
color: '#FFF',
fontSize: 18,
},
button: {
backgroundColor: '#007AFF',
padding: 15,
borderRadius: 5,
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
},
});