import React, { useEffect, useState, useCallback } from… · The Chat Archive
Explore / Programming import React, { useEffect, useState, useCallback } from 'react'; import { View,… Save Share Download ▾ Reportimport React, { useEffect, useState, useCallback } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
ActivityIndicator,
Alert,
Dimensions,
SafeAreaView,
Platform,
StatusBar as RNStatusBar
} from 'react-native';
import { useNavigation, useIsFocused } from '@react-navigation/native';
import { HistoricalFigure, Chat, Message } from '../types/types';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Ionicons } from '@expo/vector-icons';
import { StatusBar } from 'expo-status-bar';
import CustomText from '../components/CustomText';
interface ChatWithLastMessage extends Chat {
lastMessage?: string;
lastMessageTimestamp?: number;
}
const ChatListScreen = () => {
const navigation = useNavigation();
const [chats, setChats] = useState<ChatWithLastMessage[]>([]);
const [loading, setLoading] = useState(true);
const isFocused = useIsFocused();
useEffect(() => {
const fetchChats = async () => {
try {
const chatsData = await AsyncStorage.getItem('chats');
const chatsList: Chat[] = chatsData ? JSON.parse(chatsData) : [];
code Copy code
const chatsWithMessages: ChatWithLastMessage[] = await Promise.all(chatsList.map(async (chat) => {
const messagesData = await AsyncStorage.getItem(`chat_${chat.id}_messages`);
const messages: Message[] = messagesData ? JSON.parse(messagesData) : [];
const lastMessage = messages[messages.length - 1]?.text || '';
const lastTimestamp = messages[messages.length - 1]?.timestamp || chat.createdAt;
return {
...chat,
lastMessage,
lastMessageTimestamp: lastTimestamp
};
}));
const sortedChats = chatsWithMessages.sort((a, b) =>
(b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0)
);
setChats(sortedChats);
} catch (error) {
console.error('Error fetching chats:', error);
Alert.alert("Hata", "Sohbetler yüklenirken bir hata oluştu.");
} finally {
setLoading(false);
}
};
fetchChats();
}, [isFocused]);
const deleteChat = useCallback(async (chatId: string) => {
Alert.alert(
"Sohbeti Sil",
"Bu sohbeti silmek istediğinizden emin misiniz?",
[
{ text: "İptal", style: "cancel" },
{
text: "Sil",
style: "destructive",
onPress: async () => {
try {
const updatedChats = chats.filter(chat => chat.id !== chatId);
await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));
await AsyncStorage.removeItem( );
setChats(updatedChats);
} catch (error) {
console.error('Error deleting chat:', error);
Alert.alert("Hata", "Sohbet silinirken bir hata oluştu.");
}
}
}
]
);
}, [chats]);
Show full message · 523 lines Assistant2024-10-06 22:30 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Oct 6, 2024
Added to archive Nov 16, 2026
ID 01m7h41wndbn6bmmxndgg0wh79Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: d6105966fce97dcda75da5cacfc7be10
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
chat_${chatId}_messages
const deleteAllChats = useCallback(async () => {
Alert.alert(
"Tüm Sohbetleri Sil",
${chats.length} sohbet silinecek. Emin misiniz?,
[
{ text: "İptal", style: "cancel" },
{
text: "Sil",
style: "destructive",
onPress: async () => {
try {
await AsyncStorage.removeItem('chats');
for (const chat of chats) {
await AsyncStorage.removeItem(chat_${chat.id}_messages);
}
setChats([]);
} catch (error) {
console.error('Error deleting all chats:', error);
Alert.alert("Hata", "Sohbetler silinirken bir hata oluştu.");
}
}
}
]
);
}, [chats]);
const renderChatItem = useCallback(({ item }: { item: ChatWithLastMessage }) => (
<TouchableOpacity
style={styles.chatItem}
onPress={() => navigation.navigate('Chat', { chatId: item.id, figure: item.figure })}
>
<Image source={{ uri: item.figure.image }} style={styles.avatar} />
{item.figure.name}
{item.lastMessage}
{timeAgo(item.lastMessageTimestamp)}
<TouchableOpacity onPress={() => deleteChat(item.id)} style={styles.deleteButton}>
), [deleteChat]);
const keyExtractor = useCallback((item: ChatWithLastMessage) => item.id, []);
const timeAgo = (timestamp: number | undefined) => {
if (!timestamp) return '';
const now = Date.now();
const diff = Math.floor((now - timestamp) / 60000);
if (diff < 1) return Şimdi;
if (diff < 60) return ${diff} dk önce;
const hours = Math.floor(diff / 60);
if (hours < 24) return ${hours} saat önce;
const days = Math.floor(hours / 24);
return ${days} gün önce;
};
if (loading) {
return (
);
}
return (
Sohbetlerim
{chats.length > 0 && (
)}
{chats.length === 0 ? (
Hiç sohbetiniz yok! Yeni bir sohbet başlatın.
) : (
)}
<TouchableOpacity
style={styles.fab}
onPress={() => navigation.navigate('Home')}
>
);
};
const { width, height } = Dimensions.get('window');
const styles = StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: '#F8F8F8',
paddingTop: Platform.OS === 'android' ? RNStatusBar.currentHeight : 0,
},
container: {
flex: 1,
backgroundColor: '#F8F8F8',
paddingHorizontal: 15,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F8F8F8',
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 20,
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
},
title: {
fontSize: 28,
color: '#333',
fontFamily: 'Poppins_400Regular',
},
deleteAllButton: {
padding: 5,
},
chatList: {
paddingTop: 10,
paddingBottom: 80,
},
chatItem: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#FFFFFF',
borderRadius: 12,
marginBottom: 12,
marginHorizontal:3,
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
padding: 20,
},
avatar: {
width: 60,
height: 60,
borderRadius: 30,
marginRight: 16,
},
chatInfo: {
flex: 1,
},
chatName: {
fontSize: 18,
color: '#333',
fontFamily: 'Poppins_700Bold',
},
chatLastMessage: {
fontSize: 14,
color: '#666',
marginTop: 4,
fontFamily: 'Poppins_400Regular',
},
chatDate: {
fontSize: 12,
color: '#999',
marginTop: 4,
fontFamily: 'Poppins_400Regular',
},
deleteButton: {
padding: 8,
},
fab: {
position: 'absolute',
width: 56,
height: 56,
backgroundColor: '#007AFF',
borderRadius: 28,
justifyContent: 'center',
alignItems: 'center',
right: 16,
bottom: 16,
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingHorizontal: 32,
},
emptyText: {
fontSize: 16,
color: '#666',
textAlign: 'center',
fontFamily: 'Poppins_400Regular',
},
});
export default ChatListScreen; buraya her girildiğinde mavi loadingler gösteriliyor. bu böyle her girişte yüklenmesin yüklü kalsın hep. aynı zamanda mavi loadingleri kaldır güzel görünmüyor. aynı şeyi burada da yap // src/screens/HomeScreen.tsx
import React, { useEffect, useState, useCallback } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
ActivityIndicator,
Alert,
SafeAreaView,
Platform,
StatusBar as RNStatusBar
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure, Chat, Message } from '../types/types';
import { db } from '../services/firebaseConfig';
import { collection, getDocs } from 'firebase/firestore';
import AsyncStorage from '@react-native-async-storage/async-storage';
import uuid from 'react-native-uuid';
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
const HomeScreen = () => {
const navigation = useNavigation();
const [historicalFigures, setHistoricalFigures] = useState<HistoricalFigure[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchFigures = async () => {
try {
const figuresCollection = collection(db, 'figures');
const figuresSnapshot = await getDocs(figuresCollection);
const figuresList: HistoricalFigure[] = figuresSnapshot.docs.map(doc => {
const data = doc.data();
return {
id: doc.id,
name: data.name,
image: data.image,
systemPrompt: data.systemPrompt,
description: data.description || "",
} as HistoricalFigure;
});
setHistoricalFigures(figuresList);
} catch (error) {
console.error('Error fetching figures:', error);
Alert.alert("Hata", "Figürler yüklenirken bir hata oluştu.");
} finally {
setLoading(false);
}
};
code Copy code
fetchFigures();
const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
<TouchableOpacity
style={styles.figureItem}
onPress={() => startChat(item)}
>
<Image source={{ uri: item.image }} style={styles.avatar} />
{item.name}
{item.description}
), []);
const startChat = async (figure: HistoricalFigure) => {
const chatId = uuid.v4().toString();
const newChat: Chat = {
id: chatId,
figure: {
...figure,
description: figure.description || "",
},
createdAt: Date.now(),
};
code Copy code
const initialMessage: Message = {
id: uuid.v4().toString(),
text: figure.description || "Açıklama mevcut değil.",
isUser: false,
timestamp: Date.now(),
};
try {
const existingChats = await AsyncStorage.getItem('chats');
const chats: Chat[] = existingChats ? JSON.parse(existingChats) : [];
const updatedChats = [...chats, newChat];
await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));
const existingMessages = await AsyncStorage.getItem(`chat_${chatId}_messages`);
const messages: Message[] = existingMessages ? JSON.parse(existingMessages) : [];
const updatedMessages = [...messages, initialMessage];
await AsyncStorage.setItem(`chat_${chatId}_messages`, JSON.stringify(updatedMessages));
navigation.navigate('Chats', { screen: 'Chat', params: { chatId, figure } });
} catch (error) {
console.error('Error starting chat:', error);
Alert.alert("Hata", "Sohbet başlatılırken bir hata oluştu.");
}
const keyExtractor = useCallback((item: HistoricalFigure) => item.id, []);
if (loading) {
return (
);
}
return (
Tarihi Karakterler
);
};
const styles = StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: '#F5F5F5',
paddingTop: Platform.OS === 'android' ? RNStatusBar.currentHeight : 0,
},
container: {
flex: 1,
backgroundColor: '#F5F5F5',
paddingHorizontal: 15,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5F5F5',
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 20,
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
},
title: {
fontSize: 28,
color: '#333',
fontFamily: 'Poppins_700Bold',
},
infoButton: {
padding: 5,
},
figureList: {
paddingTop: 10,
},
figureItem: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#FFFFFF',
borderRadius: 12,
marginBottom: 15,
padding: 20,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.1,
shadowRadius: 3.84,
elevation: 5,
marginHorizontal:3,
},
avatar: {
width: 60,
height: 60,
borderRadius: 30,
marginRight: 15,
},
figureInfo: {
flex: 1,
},
figureName: {
fontSize: 18,
color: '#333',
fontFamily: 'Poppins_700Bold',
},
figureDescription: {
fontSize: 14,
color: '#666',
marginTop: 4,
fontFamily: 'Poppins_400Regular',
},
});
export default HomeScreen;
To enhance the user experience by preventing the blue loading indicators from appearing every time you navigate to the ChatListScreen and HomeScreen , you can adjust the data fetching logic to load data only once during the app's lifecycle. Additionally, removing or replacing the ActivityIndicator will achieve a cleaner UI.
Here's how you can implement these changes for both screens:
Load Data Only Once:
ChatListScreen : Remove the dependency on useIsFocused to prevent re-fetching data every time the screen gains focus.
HomeScreen : Ensure data is fetched only once during the initial mount.
Remove or Replace the Loading Indicators:
Remove the ActivityIndicator components to eliminate the blue loading spinners.
Optionally, you can implement a more subtle loading state or skeleton screens if desired.
Below are the updated implementations for both screens:
1. ChatListScreen
Changes Implemented:
Removed useIsFocused Dependency: This ensures that the chats are fetched only once when the component mounts, not every time the screen gains focus.
Modified Loading Logic: The loading state is managed to show the loader only during the initial data fetch.
Removed ActivityIndicator: The loading spinner is removed to provide a cleaner UI once the data is loaded.
Updated Code:
typescript Copy code
// src/screens/ChatListScreen.tsx
import React, { useEffect, useState, useCallback } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
Alert,
Dimensions,
SafeAreaView,
Platform,
StatusBar as RNStatusBar
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure, Chat, Message } from '../types/types';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Ionicons } from '@expo/vector-icons';
import { StatusBar } from 'expo-status-bar';
import CustomText from '../components/CustomText';
interface ChatWithLastMessage extends Chat {
lastMessage?: string;
lastMessageTimestamp?: number;
}
const ChatListScreen = () => {
const navigation = useNavigation();
const [chats, setChats] = useState<ChatWithLastMessage[]>([]);
const [loading, setLoading] = useState<boolean>(true); // Initially loading
useEffect(() => {
const fetchChats = async () => {
try {
const chatsData = await AsyncStorage.getItem('chats');
const chatsList: Chat[] = chatsData ? JSON.parse(chatsData) : [];
const chatsWithMessages: ChatWithLastMessage[] = await Promise.all(chatsList.map(async (chat) => {
const messagesData = await AsyncStorage.getItem(`chat_${chat.id}_messages`);
const messages: Message[] = messagesData ? JSON.parse(messagesData) : [];
const lastMessage = messages[messages.length - 1]?.text || '';
const lastTimestamp = messages[messages.length - 1]?.timestamp || chat.createdAt;
return {
...chat,
lastMessage,
lastMessageTimestamp: lastTimestamp
};
}));
const sortedChats = chatsWithMessages.sort((a, b) =>
(b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0)
);
setChats(sortedChats);
} catch (error) {
console.error('Error fetching chats:', error);
Alert.alert("Hata", "Sohbetler yüklenirken bir hata oluştu.");
} finally {
setLoading(false); // Stop loading after fetch
}
};
fetchChats();
}, []); // Removed isFocused from dependencies
const deleteChat = useCallback(async (chatId: string) => {
Alert.alert(
"Sohbeti Sil",
"Bu sohbeti silmek istediğinizden emin misiniz?",
[
{ text: "İptal", style: "cancel" },
{
text: "Sil",
style: "destructive",
onPress: async () => {
try {
const updatedChats = chats.filter(chat => chat.id !== chatId);
await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));
await AsyncStorage.removeItem(`chat_${chatId}_messages`);
setChats(updatedChats);
} catch (error) {
console.error('Error deleting chat:', error);
Alert.alert("Hata", "Sohbet silinirken bir hata oluştu.");
}
}
}
]
);
}, [chats]);
const deleteAllChats = useCallback(async () => {
Alert.alert(
"Tüm Sohbetleri Sil",
`${chats.length} sohbet silinecek. Emin misiniz?`,
[
{ text: "İptal", style: "cancel" },
{
text: "Sil",
style: "destructive",
onPress: async () => {
try {
await AsyncStorage.removeItem('chats');
for (const chat of chats) {
await AsyncStorage.removeItem(`chat_${chat.id}_messages`);
}
setChats([]);
} catch (error) {
console.error('Error deleting all chats:', error);
Alert.alert("Hata", "Sohbetler silinirken bir hata oluştu.");
}
}
}
]
);
}, [chats]);
const renderChatItem = useCallback(({ item }: { item: ChatWithLastMessage }) => (
<TouchableOpacity
style={styles.chatItem}
onPress={() => navigation.navigate('Chat', { chatId: item.id, figure: item.figure })}
>
<Image source={{ uri: item.figure.image }} style={styles.avatar} />
<View style={styles.chatInfo}>
<CustomText bold style={styles.chatName}>{item.figure.name}</CustomText>
<CustomText style={styles.chatLastMessage} numberOfLines={1}>
{item.lastMessage}
</CustomText>
<CustomText style={styles.chatDate}>{timeAgo(item.lastMessageTimestamp)}</CustomText>
</View>
<TouchableOpacity onPress={() => deleteChat(item.id)} style={styles.deleteButton}>
<Ionicons name="trash-outline" size={24} />
</TouchableOpacity>
</TouchableOpacity>
), [deleteChat]);
const keyExtractor = useCallback((item: ChatWithLastMessage) => item.id, []);
const timeAgo = (timestamp: number | undefined) => {
if (!timestamp) return '';
const now = Date.now();
const diff = Math.floor((now - timestamp) / 60000);
if (diff < 1) return `Şimdi`;
if (diff < 60) return `${diff} dk önce`;
const hours = Math.floor(diff / 60);
if (hours < 24) return `${hours} saat önce`;
const days = Math.floor(hours / 24);
return `${days} gün önce`;
};
return (
<SafeAreaView style={styles.safeArea}>
<StatusBar style="dark" />
<View style={styles.container}>
<View style={styles.header}>
<CustomText bold style={styles.title}>Sohbetlerim</CustomText>
{chats.length > 0 && (
<TouchableOpacity onPress={deleteAllChats} style={styles.deleteAllButton}>
<Ionicons name="trash-outline" size={24} color="#FF3B30" />
</TouchableOpacity>
)}
</View>
{loading ? (
// Optional: Replace with a different loading UI or remove entirely
// For this example, we'll remove the loader
<View style={styles.loadingPlaceholder}></View>
) : chats.length === 0 ? (
<View style={styles.emptyContainer}>
<CustomText style={styles.emptyText}>Hiç sohbetiniz yok! Yeni bir sohbet başlatın.</CustomText>
</View>
) : (
<FlatList
data={chats}
renderItem={renderChatItem}
keyExtractor={keyExtractor}
contentContainerStyle={styles.chatList}
/>
)}
<TouchableOpacity
style={styles.fab}
onPress={() => navigation.navigate('Home')}
>
<Ionicons name="add" size={30} color="#fff" />
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const { width, height } = Dimensions.get('window');
const styles = StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: '#F8F8F8',
paddingTop: Platform.OS === 'android' ? RNStatusBar.currentHeight : 0,
},
container: {
flex: 1,
backgroundColor: '#F8F8F8',
paddingHorizontal: 15,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F8F8F8',
},
loadingPlaceholder: {
flex: 1,
// Optional styling for placeholder
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 20,
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
},
title: {
fontSize: 28,
color: '#333',
fontFamily: 'Poppins_400Regular',
},
deleteAllButton: {
padding: 5,
},
chatList: {
paddingTop: 10,
paddingBottom: 80,
},
chatItem: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#FFFFFF',
borderRadius: 12,
marginBottom: 12,
marginHorizontal:3,
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
padding: 20,
},
avatar: {
width: 60,
height: 60,
borderRadius: 30,
marginRight: 16,
},
chatInfo: {
flex: 1,
},
chatName: {
fontSize: 18,
color: '#333',
fontFamily: 'Poppins_700Bold',
},
chatLastMessage: {
fontSize: 14,
color: '#666',
marginTop: 4,
fontFamily: 'Poppins_400Regular',
},
chatDate: {
fontSize: 12,
color: '#999',
marginTop: 4,
fontFamily: 'Poppins_400Regular',
},
deleteButton: {
padding: 8,
},
fab: {
position: 'absolute',
width: 56,
height: 56,
backgroundColor: '#007AFF',
borderRadius: 28,
justifyContent: 'center',
alignItems: 'center',
right: 16,
bottom: 16,
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingHorizontal: 32,
},
emptyText: {
fontSize: 16,
color: '#666',
textAlign: 'center',
fontFamily: 'Poppins_400Regular',
},
});
export default ChatListScreen;
Explanation of Changes:
Data Fetching Only Once:
Removed useIsFocused: The useEffect now has an empty dependency array [], meaning it runs only once when the component mounts.
Loading State Management: The loading state is initially set to true and is set to false once the data fetching is complete. This prevents the loading indicator from showing again when navigating back to the screen.
Removed Activity Indicator:
The ActivityIndicator component and its associated styles have been removed.
An optional loadingPlaceholder view is added, which can be styled to show a different loading UI if desired. For simplicity, it's left empty here.
UI Adjustments:
The main content (FlatList or empty state) is conditionally rendered based on the loading state.
If loading is false and there are no chats, an empty state message is displayed without any flashing loader.
2. HomeScreen
Changes Implemented:
Ensured Single Data Fetch: The data is fetched only once when the component mounts by maintaining the dependency array.
Removed ActivityIndicator: The loading spinner is removed to maintain consistency with the ChatListScreen.
Updated Code:
Explanation of Changes:
Data Fetching Only Once:
Empty Dependency Array: The useEffect hook in HomeScreen now has an empty dependency array [], ensuring that the figures are fetched only once when the component mounts.
Removed Activity Indicator:
The ActivityIndicator component and its associated styles have been removed.
An optional loadingPlaceholder view is added, which can be styled to show a different loading UI if desired. For simplicity, it's left empty here.
UI Adjustments:
The main content (FlatList) is conditionally rendered based on the loading state.
If loading is false, the list of historical figures is displayed. Otherwise, a placeholder view is shown (which can be customized or left empty).
Optional Enhancements
If you prefer to provide a smoother user experience during the initial loading phase without using the ActivityIndicator, consider implementing the following:
Skeleton Screens: Use skeleton placeholders that mimic the layout of the content while data is loading. Libraries like react-native-skeleton-placeholder can help achieve this.
Fade-In Animations: Gradually display the content once it's loaded to avoid abrupt changes. You can use the Animated API for this purpose.
Persistent Caching: Implement a caching mechanism using Context API or state management libraries like Redux or Recoil to persist data across different screens and sessions, reducing the need to fetch data repeatedly.
Final Thoughts
By implementing the above changes:
Performance Improvement: Fetching data only once reduces unnecessary reads from AsyncStorage and Firebase, enhancing performance.
Better User Experience: Removing the blue loading indicators provides a cleaner UI, preventing any distracting loading spinners from appearing every time users navigate between screens.
Maintainability: Keeping the data fetching logic straightforward makes the code easier to maintain and less prone to bugs related to unnecessary re-renders or state changes.
Feel free to further customize the loading experience based on your app's design requirements!
Show full message · 613 lines Copy first response
Not yet included in a published release.
// src/screens/HomeScreen.tsx
import React, { useEffect, useState, useCallback } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
Alert,
SafeAreaView,
Platform,
StatusBar as RNStatusBar
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure, Chat, Message } from '../types/types';
import { db } from '../services/firebaseConfig';
import { collection, getDocs } from 'firebase/firestore';
import AsyncStorage from '@react-native-async-storage/async-storage';
import uuid from 'react-native-uuid';
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
const HomeScreen = () => {
const navigation = useNavigation();
const [historicalFigures, setHistoricalFigures] = useState<HistoricalFigure[]>([]);
const [loading, setLoading] = useState<boolean>(true); // Initially loading
useEffect(() => {
const fetchFigures = async () => {
try {
const figuresCollection = collection(db, 'figures');
const figuresSnapshot = await getDocs(figuresCollection);
const figuresList: HistoricalFigure[] = figuresSnapshot.docs.map(doc => {
const data = doc.data();
return {
id: doc.id,
name: data.name,
image: data.image,
systemPrompt: data.systemPrompt,
description: data.description || "",
} as HistoricalFigure;
});
setHistoricalFigures(figuresList);
} catch (error) {
console.error('Error fetching figures:', error);
Alert.alert("Hata", "Figürler yüklenirken bir hata oluştu.");
} finally {
setLoading(false); // Stop loading after fetch
}
};
fetchFigures();
}, []); // Ensures it runs only once
const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
<TouchableOpacity
style={styles.figureItem}
onPress={() => startChat(item)}
>
<Image source={{ uri: item.image }} style={styles.avatar} />
<View style={styles.figureInfo}>
<CustomText bold style={styles.figureName}>{item.name}</CustomText>
<CustomText style={styles.figureDescription} numberOfLines={2}>
{item.description}
</CustomText>
</View>
<Ionicons name="chevron-forward" size={24} color="#007AFF" />
</TouchableOpacity>
), []);
const startChat = async (figure: HistoricalFigure) => {
const chatId = uuid.v4().toString();
const newChat: Chat = {
id: chatId,
figure: {
...figure,
description: figure.description || "",
},
createdAt: Date.now(),
};
const initialMessage: Message = {
id: uuid.v4().toString(),
text: figure.description || "Açıklama mevcut değil.",
isUser: false,
timestamp: Date.now(),
};
try {
const existingChats = await AsyncStorage.getItem('chats');
const chats: Chat[] = existingChats ? JSON.parse(existingChats) : [];
const updatedChats = [...chats, newChat];
await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));
const existingMessages = await AsyncStorage.getItem(`chat_${chatId}_messages`);
const messages: Message[] = existingMessages ? JSON.parse(existingMessages) : [];
const updatedMessages = [...messages, initialMessage];
await AsyncStorage.setItem(`chat_${chatId}_messages`, JSON.stringify(updatedMessages));
navigation.navigate('Chat', { chatId, figure });
} catch (error) {
console.error('Error starting chat:', error);
Alert.alert("Hata", "Sohbet başlatılırken bir hata oluştu.");
}
};
const keyExtractor = useCallback((item: HistoricalFigure) => item.id, []);
return (
<SafeAreaView style={styles.safeArea}>
<StatusBar style="dark" />
<View style={styles.container}>
<View style={styles.header}>
<CustomText bold style={styles.title}>Tarihi Karakterler</CustomText>
<TouchableOpacity style={styles.infoButton}>
<Ionicons name="information-circle-outline" size={24} color="#007AFF" />
</TouchableOpacity>
</View>
{loading ? (
// Optional: Replace with a different loading UI or remove entirely
// For this example, we'll remove the loader
<View style={styles.loadingPlaceholder}></View>
) : (
<FlatList
data={historicalFigures}
renderItem={renderFigureItem}
keyExtractor={keyExtractor}
contentContainerStyle={styles.figureList}
showsVerticalScrollIndicator={false}
/>
)}
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: '#F5F5F5',
paddingTop: Platform.OS === 'android' ? RNStatusBar.currentHeight : 0,
},
container: {
flex: 1,
backgroundColor: '#F5F5F5',
paddingHorizontal: 15,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5F5F5',
},
loadingPlaceholder: {
flex: 1,
// Optional styling for placeholder
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 20,
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
},
title: {
fontSize: 28,
color: '#333',
fontFamily: 'Poppins_700Bold',
},
infoButton: {
padding: 5,
},
figureList: {
paddingTop: 10,
},
figureItem: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#FFFFFF',
borderRadius: 12,
marginBottom: 15,
padding: 20,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.1,
shadowRadius: 3.84,
elevation: 5,
marginHorizontal:3,
},
avatar: {
width: 60,
height: 60,
borderRadius: 30,
marginRight: 15,
},
figureInfo: {
flex: 1,
},
figureName: {
fontSize: 18,
color: '#333',
fontFamily: 'Poppins_700Bold',
},
figureDescription: {
fontSize: 14,
color: '#666',
marginTop: 4,
fontFamily: 'Poppins_400Regular',
},
});
export default HomeScreen;