// src/screens/HomeScreen.tsx import React, { useCallback… · The Chat Archive
Explore / Programming // src/screens/HomeScreen.tsx import React, { useCallback, useContext, useState } from… Save Share Download ▾ Report// src/screens/HomeScreen.tsx
import React, { useCallback, useContext, useState } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
SafeAreaView,
ActivityIndicator,
useWindowDimensions,
RefreshControl,
ScrollView,
Alert,
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure } from '../types/types';
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
import { useApp } from '../context/AppContext';
import { ChatContext } from '../context/ChatContext';
import { CoinContext } from '../context/CoinContext';
import uuid from 'react-native-uuid'; // Import uuid for unique chat IDs
import AsyncStorage from '@react-native-async-storage/async-storage';
const HomeScreen = () => {
const navigation = useNavigation();
const {
historicalFigures,
loading,
refreshing,
t,
currentTheme,
refreshFigures,
categories,
} = useApp();
const { width } = useWindowDimensions();
const { addChat } = useContext(ChatContext);
const { coins, showRewardedAd } = useContext(CoinContext);
const [selectedCategory, setSelectedCategory] = useState('All');
const numColumns = 2;
const startChat = useCallback(async (figure: HistoricalFigure) => {
try {
const existingChats = await AsyncStorage.getItem('chats');
const chatsList: any[] = existingChats ? JSON.parse(existingChats) : [];
// Check if a chat with the same figure.id already exists (optional)
// If you allow multiple chats per figure, skip this check
const chatExists = chatsList.some(chat => chat.figure.id === figure.id);
if (chatExists) {
// Retrieve the existing chatId
const existingChat = chatsList.find(chat => chat.figure.id === figure.id);
if (existingChat) {
navigation.navigate('Chat', { chatId: existingChat.id, figure });
return;
}
}
const chatId = uuid.v4().toString(); // Generate a unique chat ID
// Add or initialize the chat
await addChat({
id: chatId,
figure,
createdAt: Date.now(),
});
// Navigate to ChatScreen with both chatId and figure
navigation.navigate('Chat', { chatId, figure });
} catch (error) {
console.error('Error starting chat:', error);
Alert.alert(t('error'), t('errorStartingChat'));
}
}, [addChat, navigation, t]);
const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
<TouchableOpacity
style={[styles.figureItem, { backgroundColor: currentTheme.cardBackground }]}
onPress={() => startChat(item)}
>
<Image source={{ uri: item.image }} style={styles.avatar} />
<CustomText bold style={[styles.figureName, { color: currentTheme.textColor }]}>
{item.name}
<CustomText style={[styles.figureCategory, { color: currentTheme.accentColor }]}>
{item.category}
<CustomText
style={[styles.figureDescription, { color: currentTheme.secondaryTextColor }]}
numberOfLines={3}
>
{item.description}
<CustomText style={[styles.popularity, { color: currentTheme.accentColor }]}>
{t('popularity')} {item.popularity || 0}
), [currentTheme, startChat, t]);
Assistant2024-10-19 00:00 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language —
Conversation date Oct 19, 2024
Added to archive Nov 16, 2026
ID 01m7h41yw3574yet9wkbzxjrpgSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 31e491e880a798787e310df05d6b883b
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
const keyExtractor = useCallback((item: HistoricalFigure) => item.id, []);
const onRefresh = useCallback(async () => {
await refreshFigures(); // This will handle refreshing state in AppContext
}, [refreshFigures]);
const filteredFigures = selectedCategory === 'All'
? historicalFigures
: historicalFigures.filter(fig => fig.category === selectedCategory);
const renderCategoryItem = useCallback((category: string, index: number) => {
const isSelected = category === selectedCategory;
return (
<TouchableOpacity
key={${category}-${index}} // Ensure each item has a unique key
style={[
styles.categoryButton,
{
backgroundColor: isSelected ? currentTheme.accentColor : 'transparent',
borderColor: isSelected ? currentTheme.accentColor : currentTheme.secondaryTextColor,
}
]}
onPress={() => setSelectedCategory(category)}
>
<CustomText
style={[
styles.categoryText,
{
color: isSelected ? currentTheme.backgroundColor : currentTheme.textColor,
}
]}
>
{t(category)}
);
}, [selectedCategory, currentTheme, t]);
const renderCategoryRows = () => {
// Display categories in two rows for better organization
const halfLength = Math.ceil(categories.length / 2);
return (
{categories.slice(0, halfLength).map((category, index) => renderCategoryItem(category, index))}
{categories.slice(halfLength).map((category, index) => renderCategoryItem(category, index + halfLength))}
);
};
return (
<SafeAreaView style={[styles.safeArea, { backgroundColor: currentTheme.backgroundColor }]}>
{/* Header /}
<CustomText bold style={[styles.title, { color: currentTheme.textColor }]}>
{t('historicalFigures')}
{/ Coin Display /}
<CustomText style={[styles.coinText, { color: currentTheme.textColor }]}>
{coins}
{/ Settings Button */}
<TouchableOpacity
style={styles.settingsButton}
onPress={() => navigation.navigate('Settings')}
>
{/* Category Selector (Two Rows, Scrollable Horizontally) */}
{renderCategoryRows()}
{/* Content */}
{loading ? (
// Show a single loading indicator during the initial load
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color={currentTheme.accentColor} />
</View>
) : filteredFigures.length === 0 ? (
<View style={styles.emptyContainer}>
<CustomText style={[styles.emptyText, { color: currentTheme.textColor }]}>
{t('noFiguresInThisCategory')}
</CustomText>
</View>
) : (
<FlatList
data={filteredFigures}
renderItem={renderFigureItem}
keyExtractor={keyExtractor}
contentContainerStyle={styles.figureList}
numColumns={numColumns}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={[currentTheme.accentColor]}
tintColor={currentTheme.accentColor}
/>
}
/>
)}
</View>
</SafeAreaView>
const styles = StyleSheet.create({
safeArea: {
flex: 1,
},
container: {
flex: 1,
paddingHorizontal: 10,
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 15,
paddingHorizontal: 15,
},
title: {
fontFamily: 'Poppins_700Bold',
fontSize: 24,
},
headerRight: {
flexDirection: 'row',
alignItems: 'center',
},
coinContainer: {
flexDirection: 'row',
alignItems: 'center',
padding: 5,
},
coinText: {
fontFamily: 'Poppins_700Bold',
fontSize: 18,
marginLeft: 5,
},
settingsButton: {
padding: 2,
marginLeft: 2,
},
categoryRowsContainer: {
paddingHorizontal: 5,
paddingBottom: 20,
},
categoryRow: {
flexDirection: 'row',
marginBottom: 6,
},
categoryButton: {
paddingVertical: 6,
paddingHorizontal: 8,
borderRadius: 16,
borderWidth: 1,
marginRight: 5,
},
categoryText: {
fontFamily: 'Poppins_600SemiBold',
fontSize: 14,
},
figureList: {
paddingVertical: 10,
},
figureItem: {
borderRadius: 12,
elevation: 3,
flex: 1,
margin: 5,
padding: 10,
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.22,
shadowRadius: 2.22,
shadowColor: '#000',
},
avatar: {
borderRadius: 30,
height: 100,
width: 100,
alignSelf: 'center',
marginBottom: 10,
},
figureInfo: {
alignItems: 'center',
flex: 1,
},
figureName: {
fontFamily: 'Poppins_700Bold',
fontSize: 16,
textAlign: 'center',
},
figureCategory: {
fontFamily: 'Poppins_600SemiBold',
fontSize: 12,
},
figureDescription: {
fontFamily: 'Poppins_400Regular',
fontSize: 14,
marginTop: 4,
textAlign: 'center',
},
popularity: {
fontSize: 14,
marginTop: 8,
fontFamily: 'Poppins_600SemiBold',
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
emptyText: {
fontSize: 16,
textAlign: 'center',
},
});
export default HomeScreen;
// src/context/ChatContext.tsx
import React, { createContext, useState, useEffect, useCallback, ReactNode, useContext } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Chat, Message } from '../types/types';
import { CoinContext } from './CoinContext';
import { doc, updateDoc, increment } from 'firebase/firestore';
import { db } from '../services/firebaseConfig';
interface ChatWithLastMessage extends Chat {
lastMessage?: string;
lastMessageTimestamp?: number;
}
interface ChatContextProps {
chats: ChatWithLastMessage[];
addChat: (chat: Chat, messages?: Message[]) => Promise;
updateChat: (chatId: string, message: Message) => Promise;
deleteChat: (chatId: string) => Promise;
deleteAllChats: () => Promise;
}
export const ChatContext = createContext({
chats: [],
addChat: async () => {},
updateChat: async () => {},
deleteChat: async () => {},
deleteAllChats: async () => {},
});
interface ChatProviderProps {
children: ReactNode;
}
export const ChatProvider: React.FC = ({ children }) => {
const [chats, setChats] = useState<ChatWithLastMessage[]>([]);
const { deductCoins } = useContext(CoinContext);
useEffect(() => {
const loadChats = 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 loading chats:', error);
}
};
loadChats();
const addChat = useCallback(async (chat: Chat, messages: Message[] = []): Promise => {
try {
setChats(prevChats => {
// Check if chat with same id exists
if (prevChats.some(c => c.id === chat.id)) {
console.warn(Chat with id ${chat.id} already exists. Skipping addition.);
return prevChats;
}
const newChat: ChatWithLastMessage = {
...chat,
lastMessage: messages.length > 0 ? messages[messages.length - 1].text : '',
lastMessageTimestamp: messages.length > 0 ? messages[messages.length - 1].timestamp : chat.createdAt,
};
const updatedChats = [...prevChats, newChat];
AsyncStorage.setItem('chats', JSON.stringify(updatedChats)).catch((err: Error) =>
console.error('Error updating chats in AsyncStorage:', err)
);
return updatedChats;
});
await AsyncStorage.setItem(`chat_${chat.id}_messages`, JSON.stringify(messages));
} catch (error) {
console.error('Error adding chat:', error);
}
const updateChat = useCallback(async (chatId: string, message: Message): Promise => {
try {
const messagesData = await AsyncStorage.getItem(chat_${chatId}_messages);
const messages: Message[] = messagesData ? JSON.parse(messagesData) : [];
const updatedMessages = [...messages, message];
await AsyncStorage.setItem(chat_${chatId}_messages, JSON.stringify(updatedMessages));
setChats((prevChats) => {
const updatedChats = prevChats
.map((chat) => {
if (chat.id === chatId) {
return {
...chat,
lastMessage: message.text,
lastMessageTimestamp: message.timestamp,
};
}
return chat;
})
.sort((a, b) => (b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0));
AsyncStorage.setItem('chats', JSON.stringify(updatedChats)).catch((err: Error) =>
console.error('Error updating chats in AsyncStorage:', err)
);
return updatedChats;
});
if (message.isUser) {
deductCoins(1);
}
} catch (error) {
console.error('Error updating chat:', error);
}
const deleteChat = useCallback(async (chatId: string): Promise => {
try {
const updatedChats = chats.filter((chat) => chat.id !== chatId);
setChats(updatedChats);
await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));
await AsyncStorage.removeItem(chat_${chatId}_messages);
} catch (error) {
console.error('Error deleting chat:', error);
}
}, [chats]);
const deleteAllChats = useCallback(async (): Promise => {
try {
setChats([]);
await AsyncStorage.removeItem('chats');
const keys = await AsyncStorage.getAllKeys();
const chatMessageKeys = keys.filter(
(key) => key.startsWith('chat_') && key.endsWith('_messages')
);
await AsyncStorage.multiRemove(chatMessageKeys);
} catch (error) {
console.error('Error deleting all chats:', error);
}
}, []);
return (
<ChatContext.Provider value={{ chats, addChat, updateChat, deleteChat, deleteAllChats }}>
{children}
</ChatContext.Provider>
);
};
// src/screens/ChatListScreen.tsx
import React, { useContext, useEffect, useState, useCallback } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
Alert,
SafeAreaView,
Platform, ActivityIndicator
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation, useIsFocused } from '@react-navigation/native';
import { Ionicons } from '@expo/vector-icons';
import { ChatContext, ChatWithLastMessage } from '../context/ChatContext';
import CustomText from '../components/CustomText';
import { useApp } from '../context/AppContext';
import { StackNavigationProp } from '@react-navigation/stack';
import { TabParamList } from '../navigation/types'; // Navigasyon türlerini import edin
type NavigationProp = StackNavigationProp<TabParamList, 'Chats'>;
const ChatListScreen: React.FC = () => {
const navigation = useNavigation();
const { chats, deleteChat, deleteAllChats } = useContext(ChatContext);
const [sortedChats, setSortedChats] = useState<ChatWithLastMessage[]>([]);
const [loading, setLoading] = useState(true);
const isFocused = useIsFocused();
const { t, currentTheme } = useApp();
useEffect(() => {
const sortChats = () => {
// Duplicates'ı önlemek için Map kullanarak benzersiz chat'leri saklıyoruz
const uniqueChatsMap = new Map<string, ChatWithLastMessage>();
chats.forEach(chat => {
uniqueChatsMap.set(chat.id, chat); // Aynı id'ye sahip chat'ler yalnızca sonuncusu kalır
});
const uniqueChats = Array.from(uniqueChatsMap.values());
const sorted = uniqueChats.sort(
(a, b) => (b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0)
);
setSortedChats(sorted);
setLoading(false);
};
sortChats();
const handleDeleteChat = useCallback(
(chatId: string) => {
Alert.alert(
t('deleteChat'),
t('deleteChatConfirmation'),
[
{ text: t('cancel'), style: "cancel" },
{ text: t('delete'), style: "destructive", onPress: () => deleteChat(chatId) }
]
);
},
[deleteChat, t]
);
const handleDeleteAllChats = useCallback(() => {
Alert.alert(
t('deleteAllChats'),
t('deleteAllChatsConfirmation'),
[
{ text: t('cancel'), style: "cancel" },
{ text: t('delete'), style: "destructive", onPress: deleteAllChats }
]
);
}, [deleteAllChats, t]);
const renderChatItem = useCallback(
({ item }: { item: ChatWithLastMessage }) => (
<TouchableOpacity
style={[styles.chatItem, { backgroundColor: currentTheme.cardBackground }]}
onPress={() =>
navigation.navigate('Chat', { chatId: item.id, figure: item.figure })
}
>
{item.figure?.image ? (
<Image source={{ uri: item.figure.image }} style={styles.avatar} />
) : (
)}
<CustomText bold style={[styles.chatName, { color: currentTheme.textColor }]}>
{item.figure?.name || t('unknown')}
<CustomText style={[styles.chatLastMessage, { color: currentTheme.secondaryTextColor }]} numberOfLines={1}>
{item.lastMessage || t('noMessages')}
<CustomText style={[styles.chatDate, { color: currentTheme.secondaryTextColor }]}>
{timeAgo(item.lastMessageTimestamp)}
<TouchableOpacity onPress={() => handleDeleteChat(item.id)} style={styles.deleteButton}>
),
[navigation, handleDeleteChat, currentTheme, t]
);
const keyExtractor = useCallback((item: ChatWithLastMessage) => item.id, []);
const timeAgo = useCallback((timestamp: number | undefined): string => {
if (!timestamp) return '';
const now = Date.now();
const diff = Math.floor((now - timestamp) / 60000); // difference in minutes
if (diff < 1) return t('justNow');
if (diff < 60) return t('minutesAgo').replace('{{count}}', diff.toString());
const hours = Math.floor(diff / 60);
if (hours < 24) return t('hoursAgo').replace('{{count}}', hours.toString());
const days = Math.floor(hours / 24);
return t('daysAgo').replace('{{count}}', days.toString());
}, [t]);
return (
<SafeAreaView style={[styles.safeArea, { backgroundColor: currentTheme.backgroundColor }]}>
<CustomText bold style={[styles.title, { color: currentTheme.textColor }]}>{t('myChats')}
{chats.length > 0 && (
)}
{loading ? (
) : sortedChats.length === 0 ? (
<CustomText style={[styles.emptyText, { color: currentTheme.secondaryTextColor }]}>
{t('noChatsYet')}
) : (
)}
<TouchableOpacity
style={[styles.fab, { backgroundColor: currentTheme.accentColor }]}
onPress={() => navigation.navigate('Figures', { screen: 'Home' })} // Güncellenmiş yönlendirme
>
);
};
const styles = StyleSheet.create({
safeArea: {
flex: 1,
},
container: {
flex: 1,
paddingHorizontal: 10,
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingHorizontal: 15,
paddingVertical: 15,
},
title: {
fontSize: 24,
fontFamily: 'Poppins_700Bold',
},
deleteAllButton: {
padding: 5,
},
chatList: {
paddingHorizontal: 15,
paddingBottom: 80, // FAB için boşluk bırakmak
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingHorizontal: 32,
},
emptyText: {
fontSize: 16,
textAlign: 'center',
fontFamily: 'Poppins_400Regular',
},
chatItem: {
flexDirection: 'row',
alignItems: 'center',
borderRadius: 12,
marginVertical: 8,
padding: 15,
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.1,
shadowRadius: 2,
shadowColor: '#000',
elevation: 2,
},
avatar: {
width: 50,
height: 50,
borderRadius: 25,
},
chatInfo: {
flex: 1,
marginLeft: 15,
},
chatName: {
fontSize: 16,
fontFamily: 'Poppins_700Bold',
},
chatLastMessage: {
fontSize: 14,
fontFamily: 'Poppins_400Regular',
marginTop: 2,
},
chatMeta: {
alignItems: 'flex-end',
},
chatDate: {
fontSize: 12,
fontFamily: 'Poppins_400Regular',
marginBottom: 5,
},
deleteButton: {
padding: 5,
},
fab: {
position: 'absolute',
right: 20,
bottom: 20,
width: 56,
height: 56,
borderRadius: 28,
justifyContent: 'center',
alignItems: 'center',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
});
export default ChatListScreen;
// src/context/ChatContext.tsx
import React, { createContext, useState, useEffect, useCallback, ReactNode, useContext } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Chat, Message } from '../types/types';
import { CoinContext } from './CoinContext';
import { doc, updateDoc, increment } from 'firebase/firestore';
import { db } from '../services/firebaseConfig';
interface ChatWithLastMessage extends Chat {
lastMessage?: string;
lastMessageTimestamp?: number;
}
interface ChatContextProps {
chats: ChatWithLastMessage[];
addChat: (chat: Chat, messages?: Message[]) => Promise;
updateChat: (chatId: string, message: Message) => Promise;
deleteChat: (chatId: string) => Promise;
deleteAllChats: () => Promise;
}
export const ChatContext = createContext({
chats: [],
addChat: async () => {},
updateChat: async () => {},
deleteChat: async () => {},
deleteAllChats: async () => {},
});
interface ChatProviderProps {
children: ReactNode;
}
export const ChatProvider: React.FC = ({ children }) => {
const [chats, setChats] = useState<ChatWithLastMessage[]>([]);
const { deductCoins } = useContext(CoinContext);
useEffect(() => {
const loadChats = 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 loading chats:', error);
}
};
loadChats();
const addChat = useCallback(async (chat: Chat, messages: Message[] = []): Promise => {
try {
setChats(prevChats => {
// Check if chat with same id exists
if (prevChats.some(c => c.id === chat.id)) {
console.warn(Chat with id ${chat.id} already exists. Skipping addition.);
return prevChats;
}
const newChat: ChatWithLastMessage = {
...chat,
lastMessage: messages.length > 0 ? messages[messages.length - 1].text : '',
lastMessageTimestamp: messages.length > 0 ? messages[messages.length - 1].timestamp : chat.createdAt,
};
const updatedChats = [...prevChats, newChat];
AsyncStorage.setItem('chats', JSON.stringify(updatedChats)).catch((err: Error) =>
console.error('Error updating chats in AsyncStorage:', err)
);
return updatedChats;
});
await AsyncStorage.setItem(`chat_${chat.id}_messages`, JSON.stringify(messages));
} catch (error) {
console.error('Error adding chat:', error);
}
const updateChat = useCallback(async (chatId: string, message: Message): Promise => {
try {
const messagesData = await AsyncStorage.getItem(chat_${chatId}_messages);
const messages: Message[] = messagesData ? JSON.parse(messagesData) : [];
const updatedMessages = [...messages, message];
await AsyncStorage.setItem(chat_${chatId}_messages, JSON.stringify(updatedMessages));
setChats((prevChats) => {
const updatedChats = prevChats
.map((chat) => {
if (chat.id === chatId) {
return {
...chat,
lastMessage: message.text,
lastMessageTimestamp: message.timestamp,
};
}
return chat;
})
.sort((a, b) => (b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0));
AsyncStorage.setItem('chats', JSON.stringify(updatedChats)).catch((err: Error) =>
console.error('Error updating chats in AsyncStorage:', err)
);
return updatedChats;
});
if (message.isUser) {
deductCoins(1);
}
} catch (error) {
console.error('Error updating chat:', error);
}
const deleteChat = useCallback(async (chatId: string): Promise => {
try {
const updatedChats = chats.filter((chat) => chat.id !== chatId);
setChats(updatedChats);
await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));
await AsyncStorage.removeItem(chat_${chatId}_messages);
} catch (error) {
console.error('Error deleting chat:', error);
}
}, [chats]);
const deleteAllChats = useCallback(async (): Promise => {
try {
setChats([]);
await AsyncStorage.removeItem('chats');
const keys = await AsyncStorage.getAllKeys();
const chatMessageKeys = keys.filter(
(key) => key.startsWith('chat_') && key.endsWith('_messages')
);
await AsyncStorage.multiRemove(chatMessageKeys);
} catch (error) {
console.error('Error deleting all chats:', error);
}
}, []);
return (
<ChatContext.Provider value={{ chats, addChat, updateChat, deleteChat, deleteAllChats }}>
{children}
</ChatContext.Provider>
);
};
burada şöyle bir sıkıntı var aynı figür ile ana sayfadan yebi bir sohbet açmak istediğimde en son konuşulan sohbete dönüyor. ana sayfadan her figüre tıklandığında yeni bi sohbet açmasını istiyorum. ayrıca WARN Chat with id d36975bf-8bf0-4472-841c-c57243415e3a already exists. Skipping addition.
böyle bir hata veriyor
To address the issues you're encountering in your React Native application, let's break down the problems and provide comprehensive solutions:
Issue 1: Preventing Multiple Chats for the Same Figure
Problem:
Your current implementation in HomeScreen.tsx checks if a chat with the same figure.id already exists. If it does, it navigates to the existing chat instead of creating a new one. This behavior prevents multiple chats from being created for the same historical figure.
Error Message:
WARN Chat with id d36975bf-8bf0-4472-841c-c57243415e3a already exists. Skipping addition.
Solution:
To allow multiple chats with the same figure, you need to remove the logic that checks for existing chats with the same figure.id. Instead, always create a new chat with a unique chatId each time a figure is clicked.
Steps to Implement:
Remove the Existing Chat Check in HomeScreen.tsx:
Modify the startChat function to eliminate the check for existing chats with the same figure.id. This ensures that each click on a figure results in a new chat being created.
Ensure Unique chatId Generation:
Make sure that uuid.v4() is correctly generating unique IDs for each chat.
Here's how you can modify the startChat function:
// src/screens/HomeScreen.tsx
const startChat = useCallback(async (figure: HistoricalFigure) => {
try {
// Generate a new unique chat ID for every new chat
const chatId = uuid.v4().toString();
// Add the new chat
await addChat({
id: chatId,
figure,
createdAt: Date.now(),
});
// Navigate to ChatScreen with the new chatId and figure
navigation.navigate('Chat', { chatId, figure });
} catch (error) {
console.error('Error starting chat:', error);
Alert.alert(t('error'), t('errorStartingChat'));
}
}, [addChat, navigation, t]);
Remove the Existing Chat Check:
Remove or comment out the following lines in the startChat function:
// const existingChats = await AsyncStorage.getItem('chats');
// const chatsList: any[] = existingChats ? JSON.parse(existingChats) : [];
// const chatExists = chatsList.some(chat => chat.figure.id === figure.id);
// if (chatExists) {
// const existingChat = chatsList.find(chat => chat.figure.id === figure.id);
// if (existingChat) {
// navigation.navigate('Chat', { chatId: existingChat.id, figure });
// return;
// }
// }
Issue 2: Handling Duplicate Chat IDs
Problem:
You're receiving a warning about duplicate chat IDs, which indicates that the same chatId is being used more than once. This typically happens if the chatId generated by uuid.v4() isn't unique or if there's a logic error causing the same ID to be reused.
Solution:
Ensure that uuid.v4() is correctly imported and used to generate truly unique IDs. Additionally, verify that the ChatContext isn't inadvertently reusing IDs.
Steps to Implement:
Verify UUID Generation:
Ensure that uuid.v4() is correctly generating unique IDs. You can test this by logging the generated IDs.
const chatId = uuid.v4().toString();
console.log('Generated chatId:', chatId);
Check ChatContext for Logic Errors:
Make sure that the addChat function in ChatContext doesn't have any unintended logic that might reuse or duplicate IDs.
Review ChatContext:
// src/context/ChatContext.tsx
import uuid from 'react-native-uuid'; // Ensure this is correctly imported
// ... existing code ...
const addChat = useCallback(async (chat: Chat, messages: Message[] = []): Promise<void> => {
try {
setChats(prevChats => {
// Ensure chat IDs are unique
if (prevChats.some(c => c.id === chat.id)) {
console.warn(`Chat with id ${chat.id} already exists. Skipping addition.`);
return prevChats;
}
const newChat: ChatWithLastMessage = {
...chat,
lastMessage: messages.length > 0 ? messages[messages.length - 1].text : '',
lastMessageTimestamp: messages.length > 0 ? messages[messages.length - 1].timestamp : chat.createdAt,
};
const updatedChats = [...prevChats, newChat];
AsyncStorage.setItem('chats', JSON.stringify(updatedChats)).catch((err: Error) =>
console.error('Error updating chats in AsyncStorage:', err)
);
return updatedChats;
});
await AsyncStorage.setItem(`chat_${chat.id}_messages`, JSON.stringify(messages));
} catch (error) {
console.error('Error adding chat:', error);
}
}, []);
Ensure Correct UUID Usage:
Confirm that every new chat has a unique ID by using uuid.v4(). If you suspect that uuid.v4() isn't generating unique IDs, consider using another method or library to generate UUIDs.
Additional Recommendations:
Error Handling and Logging:
Add more granular logging to identify where duplicate IDs might be originating. This can help trace the issue if it persists.
Testing:
After making the changes, thoroughly test the chat creation process by initiating multiple chats with the same and different figures to ensure that each chat is uniquely created and navigated to without errors.
Code Clean-Up:
Remove any unused imports or redundant code fragments to keep the codebase clean and maintainable.
Final Revised HomeScreen.tsx
Here's the updated HomeScreen.tsx with the necessary changes applied:
// src/screens/HomeScreen.tsx
import React, { useCallback, useContext, useState } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
SafeAreaView,
ActivityIndicator,
useWindowDimensions,
RefreshControl,
ScrollView,
Alert,
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure } from '../types/types';
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
import { useApp } from '../context/AppContext';
import { ChatContext } from '../context/ChatContext';
import { CoinContext } from '../context/CoinContext';
import uuid from 'react-native-uuid'; // Ensure correct import
import AsyncStorage from '@react-native-async-storage/async-storage';
const HomeScreen = () => {
const navigation = useNavigation();
const {
historicalFigures,
loading,
refreshing,
t,
currentTheme,
refreshFigures,
categories,
} = useApp();
const { width } = useWindowDimensions();
const { addChat } = useContext(ChatContext);
const { coins, showRewardedAd } = useContext(CoinContext);
const [selectedCategory, setSelectedCategory] = useState<string>('All');
const numColumns = 2;
const startChat = useCallback(async (figure: HistoricalFigure) => {
try {
// Generate a new unique chat ID for every new chat
const chatId = uuid.v4().toString();
console.log('Generated chatId:', chatId); // Logging for debugging
// Add the new chat
await addChat({
id: chatId,
figure,
createdAt: Date.now(),
});
// Navigate to ChatScreen with the new chatId and figure
navigation.navigate('Chat', { chatId, figure });
} catch (error) {
console.error('Error starting chat:', error);
Alert.alert(t('error'), t('errorStartingChat'));
}
}, [addChat, navigation, t]);
const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
<TouchableOpacity
style={[styles.figureItem, { backgroundColor: currentTheme.cardBackground }]}
onPress={() => startChat(item)}
>
<Image source={{ uri: item.image }} style={styles.avatar} />
<View style={styles.figureInfo}>
<CustomText bold style={[styles.figureName, { color: currentTheme.textColor }]}>
{item.name}
</CustomText>
<CustomText style={[styles.figureCategory, { color: currentTheme.accentColor }]}>
{item.category}
</CustomText>
<CustomText
style={[styles.figureDescription, { color: currentTheme.secondaryTextColor }]}
numberOfLines={3}
>
{item.description}
</CustomText>
<CustomText style={[styles.popularity, { color: currentTheme.accentColor }]}>
{t('popularity')} {item.popularity || 0}
</CustomText>
</View>
</TouchableOpacity>
), [currentTheme, startChat, t]);
const keyExtractor = useCallback((item: HistoricalFigure) => item.id, []);
const onRefresh = useCallback(async () => {
await refreshFigures(); // This will handle refreshing state in AppContext
}, [refreshFigures]);
const filteredFigures = selectedCategory === 'All'
? historicalFigures
: historicalFigures.filter(fig => fig.category === selectedCategory);
const renderCategoryItem = useCallback((category: string, index: number) => {
const isSelected = category === selectedCategory;
return (
<TouchableOpacity
key={`${category}-${index}`} // Ensure each item has a unique key
style={[
styles.categoryButton,
{
backgroundColor: isSelected ? currentTheme.accentColor : 'transparent',
borderColor: isSelected ? currentTheme.accentColor : currentTheme.secondaryTextColor,
}
]}
onPress={() => setSelectedCategory(category)}
>
<CustomText
style={[
styles.categoryText,
{
color: isSelected ? currentTheme.backgroundColor : currentTheme.textColor,
}
]}
>
{t(category)}
</CustomText>
</TouchableOpacity>
);
}, [selectedCategory, currentTheme, t]);
const renderCategoryRows = () => {
// Display categories in two rows for better organization
const halfLength = Math.ceil(categories.length / 2);
return (
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.categoryRowsContainer}
>
<View>
<View style={styles.categoryRow}>
{categories.slice(0, halfLength).map((category, index) => renderCategoryItem(category, index))}
</View>
<View style={styles.categoryRow}>
{categories.slice(halfLength).map((category, index) => renderCategoryItem(category, index + halfLength))}
</View>
</View>
</ScrollView>
);
};
return (
<SafeAreaView style={[styles.safeArea, { backgroundColor: currentTheme.backgroundColor }]}>
<StatusBar style={currentTheme.statusBarStyle} />
<View style={styles.container}>
{/* Header */}
<View style={styles.header}>
<CustomText bold style={[styles.title, { color: currentTheme.textColor }]}>
{t('historicalFigures')}
</CustomText>
<View style={styles.headerRight}>
{/* Coin Display */}
<TouchableOpacity style={styles.coinContainer} onPress={showRewardedAd}>
<Ionicons name="flash" size={20} color={currentTheme.accentColor} />
<CustomText style={[styles.coinText, { color: currentTheme.textColor }]}>
{coins}
</CustomText>
</TouchableOpacity>
{/* Settings Button */}
<TouchableOpacity
style={styles.settingsButton}
onPress={() => navigation.navigate('Settings')}
>
<Ionicons name="settings-outline" size={24} color={currentTheme.accentColor} />
</TouchableOpacity>
</View>
</View>
{/* Category Selector (Two Rows, Scrollable Horizontally) */}
{renderCategoryRows()}
{/* Content */}
{loading ? (
// Show a single loading indicator during the initial load
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color={currentTheme.accentColor} />
</View>
) : filteredFigures.length === 0 ? (
<View style={styles.emptyContainer}>
<CustomText style={[styles.emptyText, { color: currentTheme.textColor }]}>
{t('noFiguresInThisCategory')}
</CustomText>
</View>
) : (
<FlatList
data={filteredFigures}
renderItem={renderFigureItem}
keyExtractor={keyExtractor}
contentContainerStyle={styles.figureList}
numColumns={numColumns}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={[currentTheme.accentColor]}
tintColor={currentTheme.accentColor}
/>
}
/>
)}
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
safeArea: {
flex: 1,
},
container: {
flex: 1,
paddingHorizontal: 10,
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 15,
paddingHorizontal: 15,
},
title: {
fontFamily: 'Poppins_700Bold',
fontSize: 24,
},
headerRight: {
flexDirection: 'row',
alignItems: 'center',
},
coinContainer: {
flexDirection: 'row',
alignItems: 'center',
padding: 5,
},
coinText: {
fontFamily: 'Poppins_700Bold',
fontSize: 18,
marginLeft: 5,
},
settingsButton: {
padding: 2,
marginLeft: 2,
},
categoryRowsContainer: {
paddingHorizontal: 5,
paddingBottom: 20,
},
categoryRow: {
flexDirection: 'row',
marginBottom: 6,
},
categoryButton: {
paddingVertical: 6,
paddingHorizontal: 8,
borderRadius: 16,
borderWidth: 1,
marginRight: 5,
},
categoryText: {
fontFamily: 'Poppins_600SemiBold',
fontSize: 14,
},
figureList: {
paddingVertical: 10,
},
figureItem: {
borderRadius: 12,
elevation: 3,
flex: 1,
margin: 5,
padding: 10,
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.22,
shadowRadius: 2.22,
shadowColor: '#000',
},
avatar: {
borderRadius: 30,
height: 100,
width: 100,
alignSelf: 'center',
marginBottom: 10,
},
figureInfo: {
alignItems: 'center',
flex: 1,
},
figureName: {
fontFamily: 'Poppins_700Bold',
fontSize: 16,
textAlign: 'center',
},
figureCategory: {
fontFamily: 'Poppins_600SemiBold',
fontSize: 12,
},
figureDescription: {
fontFamily: 'Poppins_400Regular',
fontSize: 14,
marginTop: 4,
textAlign: 'center',
},
popularity: {
fontSize: 14,
marginTop: 8,
fontFamily: 'Poppins_600SemiBold',
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
emptyText: {
fontSize: 16,
textAlign: 'center',
},
});
export default HomeScreen;
Verifying the Changes:
After implementing the above changes, conduct thorough testing to ensure that:
Multiple Chats: You can create multiple chats for the same historical figure without being redirected to an existing chat.
Unique IDs: Each chat has a unique chatId, and you no longer encounter the duplicate ID warning.
Navigation: Navigating between chats works seamlessly without errors.
Understanding the Root Cause:
The original logic in HomeScreen.tsx was preventing the creation of multiple chats for the same figure by checking if a chat with the same figure.id existed. This check was causing the application to reuse the same chat ID, leading to the duplicate ID warning when attempting to add a new chat with an already existing chatId.
By removing this check, you allow the creation of multiple chats for the same figure, each with a unique chatId. This ensures that the application behaves as expected and eliminates the warning about duplicate chat IDs.
Final Thoughts:
It's essential to design chat systems considering whether multiple conversations with the same entity are required. In scenarios where unique interactions are necessary (e.g., separate conversations with the same historical figure), ensuring the uniqueness of chat identifiers is crucial.
Always validate that unique IDs are genuinely unique and that your logic doesn't inadvertently reuse IDs, especially when generating them dynamically.
By following the above steps, you should be able to resolve both the navigation issue and the duplicate chat ID warning in your application. If you encounter further issues, consider adding more detailed logging or using debugging tools to trace the flow of chat creation and navigation.
Copy first response
Not yet included in a published release.