import React, { useState, useEffect } from 'react'; import { View, Text, TextInput, Button, FlatList, ActivityIndicator } from 'react-native'; import AsyncStorage from '@react-native-async-storage/async-storage'; import io from 'socket.io-client' import { useTailwind } from 'tailwind-rn'; function ConversationScreen({ route, navigation }) { const { otherUserId } = route.params; const [directMessages, setDirectMessages] = useState([]); const [isLoading, setIsLoading] = useState(false); const [errorMessage, setErrorMessage] = useState(''); const [newMessage, setNewMessage] = useState(''); const tailwind = useTailwind(); async function fetchDirectMessages() { setIsLoading(true); try { const token = await AsyncStorage.getItem('token'); const apiUrl = await AsyncStorage.getItem('apiEndpoint') const response = await fetch(`${apiUrl}/api/v1/app/dms/${otherUserId}`, { headers: { 'Authorization': token }, }); if (!response.ok) { throw new Error(`Failed to fetch direct messages: ${response.status}`); } const messages = await response.json(); setDirectMessages(messages); } catch (error) { console.error('Error:', error); setErrorMessage(error.message); } finally { setIsLoading(false); } } async function handleSendMessage() { const token = await AsyncStorage.getItem('token'); const senderId = await AsyncStorage.getItem('userID'); const apiUrl = await AsyncStorage.getItem('apiEndpoint') const response = await fetch(`${apiUrl}/api/v1/app/dms/send`, { method: 'POST', headers: { 'Authorization': token, 'Content-Type': 'application/json', }, body: JSON.stringify({ recipientId: otherUserId, text: newMessage, senderId: senderId }), }); if (!response.ok) { throw new Error(`Failed to send message: ${response.status}`); } const message = await response.json(); setNewMessage(''); } useEffect(() => { async function setupSocket() { const senderId = await AsyncStorage.getItem('userID'); console.log('Sender ID:', senderId); const apiUrl = await AsyncStorage.getItem('apiEndpoint') const socket = io(apiUrl); socket.emit('user connected', senderId); socket.on('new_dm', (newDm) => { setDirectMessages(prevMessages => [...prevMessages, newDm]); }); } async function setup() { await fetchDirectMessages(); await setupSocket(); } setup(); }, []); return ( {/* Display a loading indicator while the messages are being fetched */} {isLoading && } {errorMessage !== '' && {errorMessage}} {/* Render the list of direct messages */} item._id} renderItem={({ item }) => ( {item.sender.username}: {item.content} )} /> {/* Render the text input and send button */}