import { Image, StyleSheet, Button, ActivityIndicator, TextInput, Alert } from 'react-native'; import ParallaxScrollView from '@/components/ParallaxScrollView'; import { ThemedText } from '@/components/ThemedText'; import { ThemedView } from '@/components/ThemedView'; import { useEffect, useState } from 'react'; import NetInfo from '@react-native-community/netinfo'; interface Message { title: string; type: string; additionally: { payload: string; }; } interface Data { users: string[]; messages: Message[]; } export default function HomeScreen() { const [groupData, setGroupData] = useState(null); const [newMessageTitle, setNewMessageTitle] = useState(''); const [newMessagePayload, setNewMessagePayload] = useState(''); const [isSyncing, setIsSyncing] = useState(false); const fetchData = async () => { try { const response = await fetch("http://127.0.0.1:8099/grouphash:1/reloadDataFromServer"); const data: Data = await response.json(); setGroupData(data); } catch (error) { console.log('Fetch error:', error); } }; const addNewMessage = async () => { if (!newMessageTitle || !newMessagePayload) { Alert.alert("Error", "Please fill in both the title and the content of the message."); return; } const newMessage: Message = { title: newMessageTitle, type: "text", additionally: { payload: newMessagePayload, } }; // Мгновенное обновление локального состояния setGroupData(prevData => { if (prevData) { return { ...prevData, messages: [...prevData.messages, newMessage], }; } return null; }); setNewMessageTitle(''); setNewMessagePayload(''); // Отправка новой заметки на сервер try { await fetch("http://127.0.0.1:8099/grouphash:1/addMessage", { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(newMessage), }); } catch (error) { console.log('Error syncing new message:', error); } }; useEffect(() => { const syncWithServer = async () => { setIsSyncing(true); await fetchData(); setIsSyncing(false); }; const unsubscribe = NetInfo.addEventListener(state => { if (state.isConnected) { syncWithServer(); } }); // Первоначальная загрузка данных syncWithServer(); return () => { unsubscribe(); }; }, []); return ( }> Пользователи {groupData?.users.map((user, index) => ( {user} ))} {isSyncing ? : groupData?.messages.map((message, index) => ( {message.title} { message.type === "text" ? {message.additionally.payload} : !!! Please Update Program !!! } )) }