Modify ChatContext.tsx to Stabilize addChat Function:
-
Use Functional Updates: By using a functional state update with setChats, you can avoid including chats in the dependency array. This ensures that the addChat function reference remains stable.
-
Remove chats from Dependencies: Update the useCallback hook to have an empty dependency array since functional updates handle the current state internally.
Updated ChatContext.tsx:
// src/context/ChatContext.tsx
import React, { createContext, useState, useEffect, useCallback, ReactNode } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Chat, Message } from '../types/types';
interface ChatWithLastMessage extends Chat {
lastMessage?: string;
lastMessageTimestamp?: number;
}
interface ChatContextProps {
chats: ChatWithLastMessage[];
addChat: (chat: Chat, messages?: Message[]) => Promise<void>;
updateChat: (chatId: string, message: Message) => Promise<void>;
deleteChat: (chatId: string) => Promise<void>;
deleteAllChats: () => Promise<void>;
}
export const ChatContext = createContext<ChatContextProps>({
chats: [],
addChat: async () => {},
updateChat: async () => {},
deleteChat: async () => {},
deleteAllChats: async () => {},
});
interface ChatProviderProps {
children: ReactNode;
}
export const ChatProvider: React.FC<ChatProviderProps> = ({ children }) => {
const [chats, setChats] = useState<ChatWithLastMessage[]>([]);
// Load chats from AsyncStorage on mount
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();
}, []);
// Add a new chat
const addChat = useCallback(async (chat: Chat, messages: Message[] = []) => {
try {
const newChat: ChatWithLastMessage = {
...chat,
lastMessage: messages.length > 0 ? messages[messages.length - 1].text : '',
lastMessageTimestamp: messages.length > 0 ? messages[messages.length - 1].timestamp : chat.createdAt,
};
setChats((prevChats) => {
const updatedChats = [...prevChats, newChat];
AsyncStorage.setItem('chats', JSON.stringify(updatedChats)).catch((err) =>
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);
}
}, []); // Removed 'chats' from dependency array
// Update an existing chat with a new message
const updateChat = useCallback(async (chatId: string, message: Message) => {
try {
// Retrieve existing messages
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));
// Update chat's last message and timestamp
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));
// Persist updated chats
AsyncStorage.setItem('chats', JSON.stringify(updatedChats)).catch((err) =>
console.error('Error updating chats in AsyncStorage:', err)
);
return updatedChats;
});
} catch (error) {
console.error('Error updating chat:', error);
}
}, []);
// Delete a specific chat
const deleteChat = useCallback(async (chatId: string) => {
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]);
// Delete all chats
const deleteAllChats = useCallback(async () => {
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>
);
};
Explanation:
- Functional State Update: By using
setChats((prevChats) => { ... }), you ensure that you're always working with the latest state without needing to include chats in the dependency array.
- Stable
addChat Reference: With an empty dependency array [], the addChat function won't change its reference unless the component unmounts and remounts. This prevents the useEffect in ChatScreen from re-running on every chat update.
Ensure useEffect in ChatScreen.tsx Doesn't Depend on Changing Functions:
With the addChat function now having a stable reference, you can safely include it in the dependency array without causing unwanted re-renders. However, it's also good practice to ensure that your useEffect only runs when necessary.
Updated ChatScreen.tsx:
// src/screens/ChatScreen.tsx
import React, { useState, useEffect, useRef, useCallback, useContext } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
TextInput,
StyleSheet,
KeyboardAvoidingView,
Platform,
Dimensions,
ScrollView,
Alert,
ActivityIndicator,
} from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import LottieView from 'lottie-react-native';
import Markdown from 'react-native-markdown-display';
import { HistoricalFigure, Message } from '../types/types';
import { fetchAIResponse } from '../services/openaiService';
import uuid from 'react-native-uuid';
import MessageItem from '../components/MessageItem';
import { Ionicons } from '@expo/vector-icons';
import CustomText from '../components/CustomText';
import * as Clipboard from 'expo-clipboard';
import { ChatContext } from '../context/ChatContext';
import AsyncStorage from '@react-native-async-storage/async-storage';
interface RouteParams {
chatId: string;
figure: HistoricalFigure;
}
interface APIMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
const { width, height } = Dimensions.get('window');
const ChatScreen = () => {
const navigation = useNavigation();
const route = useRoute();
const { chatId, figure } = route.params as RouteParams;
const { updateChat, addChat, chats } = useContext(ChatContext);
const [messages, setMessages] = useState<Message[]>([]);
const [inputText, setInputText] = useState<string>('');
const [isTyping, setIsTyping] = useState<boolean>(false);
const [followUpQuestions, setFollowUpQuestions] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState<boolean>(false);
const flatListRef = useRef<FlatList>(null);
const isInitialLoad = useRef<boolean>(false); // Added ref to track initial load
// Fallback follow-up questions
const sampleFollowUpQuestions = [
'Bu konuda daha fazla detay öğrenmek ister misiniz?',
'Başka ne hakkında konuşmak istersiniz?',
'Farklı bir perspektif mi istiyorsunuz?',
];
useEffect(() => {
if (isInitialLoad.current) return; // Prevent re-running on updates
const loadMessages = async () => {
try {
setIsLoading(true);
setMessages([]);
setFollowUpQuestions([]);
setIsTyping(false);
const messagesData = await AsyncStorage.getItem(`chat_${chatId}_messages`);
let msgs: Message[] = messagesData ? JSON.parse(messagesData) : [];
if (msgs.length === 0) {
const conversationStarters = [
'Merhaba! Bugün nasıl yardımcı olabilirim?',
`${figure.name} hakkında ne öğrenmek istersiniz?`,
`${figure.name} ile ilgili herhangi bir sorunuz var mı?`,
];
const starterMessages: Message[] = conversationStarters.map((starter) => ({
id: uuid.v4().toString(),
text: starter,
isUser: false,
timestamp: Date.now(),
}));
msgs = starterMessages;
// Initialize the chat in context with all starter messages
const newChat = {
id: chatId,
figure: figure, // Assuming `figure` includes necessary details
createdAt: Date.now(),
};
await addChat(newChat, starterMessages); // Add all starter messages
}
// Ensure all message IDs are unique (optional defensive check)
const uniqueMsgs = Array.from(new Map(msgs.map(item => [item.id, item])).values());
setMessages(uniqueMsgs);
setIsLoading(false);
// Scroll to latest message
setTimeout(() => {
flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
}, 100);
} catch (error) {
console.error('Error loading messages:', error);
setIsLoading(false);
}
};
loadMessages();
isInitialLoad.current = true; // Mark as loaded
}, [chatId, figure.name, addChat, figure]);
const saveMessages = useCallback(async (updatedMessages: Message[]) => {
try {
await AsyncStorage.setItem(`chat_${chatId}_messages`, JSON.stringify(updatedMessages));
} catch (error) {
console.error('Error saving messages:', error);
}
}, [chatId]);
const generateFollowUpQuestions = useCallback(async (aiResponse: string) => {
try {
const prompt = `Yapay zekanın aşağıdaki yanıtına dayanarak sadece üç tane takip sorusu oluştur. Sadece sorular olmalı, açıklayıcı metin veya ek bilgiler eklemeyin.\n\nYanıt: "${aiResponse}"\n\nTakip Soruları:`;
const aiMessages: APIMessage[] = [
{
role: 'system',
content: 'Sen, yardımsever ve bilgilendirici bir yapay zeka asistanısın.',
},
{
role: 'user',
content: prompt,
},
];
const followUpResponse = await fetchAIResponse(aiMessages);
const rawQuestions = followUpResponse
.split('\n')
.map((q) => q.trim())
.filter((q) => q.length > 0)
.slice(0, 3);
const cleanQuestion = (question: string) => {
return question.replace(/^\d+\.\s*/, '');
};
const cleanedQuestions = rawQuestions.map(cleanQuestion);
if (cleanedQuestions.length < 3) {
setFollowUpQuestions([
...cleanedQuestions,
...sampleFollowUpQuestions.slice(0, 3 - cleanedQuestions.length),
]);
} else {
setFollowUpQuestions(cleanedQuestions);
}
} catch (error) {
console.error('Error generating follow-up questions:', error);
setFollowUpQuestions(sampleFollowUpQuestions);
}
}, []);
const sendMessage = useCallback(
async (text?: string) => {
const messageText = text !== undefined ? text : inputText;
if (messageText.trim() === '') return;
const userMessage: Message = {
id: uuid.v4().toString(),
text: messageText,
isUser: true,
timestamp: Date.now(),
};
const updatedMessages = [userMessage, ...messages];
setMessages(updatedMessages);
setInputText('');
setIsTyping(true);
setFollowUpQuestions([]); // Clear follow-up questions
await saveMessages(updatedMessages);
// Update the chat's last message and timestamp via context
await updateChat(chatId, userMessage);
const apiMessages: APIMessage[] = [
{
role: 'system',
content: figure.systemPrompt,
},
...updatedMessages
.slice()
.reverse()
.map((msg) => ({
role: msg.isUser ? 'user' : 'assistant',
content: msg.text,
})),
];
console.log('==== Sending Messages to AI ====');
apiMessages.forEach((msg, index) => {
console.log(`Message ${index + 1}: [${msg.role}] ${msg.content}`);
});
console.log('===============================');
try {
const aiResponse = await fetchAIResponse(apiMessages);
const aiMessage: Message = {
id: uuid.v4().toString(),
text: aiResponse,
isUser: false,
timestamp: Date.now(),
};
const newMessages = [aiMessage, ...updatedMessages];
setMessages(newMessages);
await saveMessages(newMessages);
// Update chat's last message and timestamp via context
await updateChat(chatId, aiMessage);
await generateFollowUpQuestions(aiResponse);
} catch (error) {
console.error('Error fetching AI response:', error);
Alert.alert('Hata', 'Yapay zeka yanıtı alınırken bir hata oluştu. Lütfen daha sonra tekrar deneyin.');
} finally {
setIsTyping(false);
// Scroll to the latest message
flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
}
},
[
inputText,
messages,
figure.systemPrompt,
saveMessages,
generateFollowUpQuestions,
updateChat,
chatId,
]
);
const handleFollowUpPress = (question: string) => {
sendMessage(question);
};
const renderMessageItem = useCallback(
({ item }: { item: Message }) => (
<MessageItem
message={item}
onLongPress={() => {
Clipboard.setString(item.text);
Alert.alert('Kopyalandı', 'Mesaj panoya kopyalandı!');
}}
/>
),
[]
);
const keyExtractor = useCallback((item: Message) => item.id, []);
useEffect(() => {
if (messages.length > 0) {
flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
}
}, [messages]);
return (
<KeyboardAvoidingView
style={styles.container}
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
keyboardVerticalOffset={Platform.OS === 'ios' ? 60 : 0}
>
<View style={styles.header}>
<TouchableOpacity onPress={() => navigation.goBack()} style={styles.backButton}>
<Ionicons name="arrow-back" size={28} color="#000" />
</TouchableOpacity>
<Image source={{ uri: figure.image }} style={styles.headerAvatar} />
<View style={styles.headerInfo}>
<CustomText bold style={styles.headerName}>
{figure.name}
</CustomText>
<CustomText style={styles.headerDescription} numberOfLines={1}>
{figure.description}
</CustomText>
</View>
</View>
{isLoading ? (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#007AFF" />
</View>
) : (
<FlatList
ref={flatListRef}
data={messages}
renderItem={renderMessageItem}
keyExtractor={keyExtractor}
style={styles.messageList}
contentContainerStyle={styles.messageListContent}
inverted
/>
)}
{isTyping && (
<View style={styles.typingIndicator}>
<LottieView
source={require('../../assets/typing-animation.json')}
autoPlay
loop
style={styles.typingAnimation}
/>
</View>
)}
{followUpQuestions.length > 0 && (
<View style={styles.followUpContainer}>
<CustomText bold style={styles.followUpTitle}>
Takip Soruları:
</CustomText>
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
{followUpQuestions.map((question, index) => (
<TouchableOpacity
key={index}
style={styles.followUpButton}
onPress={() => handleFollowUpPress(question)}
>
<CustomText style={styles.followUpText}>{question}</CustomText>
</TouchableOpacity>
))}
</ScrollView>
</View>
)}
<View style={styles.inputContainer}>
<TextInput
style={styles.input}
value={inputText}
onChangeText={setInputText}
placeholder="Mesajınızı yazın..."
onSubmitEditing={() => sendMessage()}
returnKeyType="send"
/>
<TouchableOpacity onPress={() => sendMessage()} style={styles.sendButton}>
<Ionicons name="send" size={24} color="#fff" />
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
backButton: {
marginRight: 10,
},
container: {
backgroundColor: '#F5F5F5',
flex: 1,
},
followUpButton: {
backgroundColor: '#E0E0E0',
borderRadius: 15,
marginRight: 10,
paddingHorizontal: 12,
paddingVertical: 8,
},
followUpContainer: {
backgroundColor: '#FFFFFF',
borderTopColor: '#E0E0E0',
borderTopWidth: 1,
padding: 10,
},
followUpText: {
color: '#000',
fontFamily: 'Poppins_400Regular',
},
followUpTitle: {
color: '#000',
fontFamily: 'Poppins_700Bold',
fontSize: 16,
marginBottom: 5,
},
header: {
alignItems: 'center',
backgroundColor: '#FFFFFF',
borderBottomColor: '#E0E0E0',
borderBottomWidth: 1,
flexDirection: 'row',
padding: 15,
paddingTop: Platform.OS === 'ios' ? 50 : 30,
},
headerAvatar: {
borderRadius: 20,
height: 40,
marginRight: 10,
width: 40,
},
headerDescription: {
color: '#666666',
fontFamily: 'Poppins_400Regular',
fontSize: 14,
marginTop: 2,
},
headerInfo: {
flex: 1,
},
headerName: {
color: '#000000',
fontFamily: 'Poppins_700Bold',
fontSize: 18,
},
input: {
backgroundColor: '#F0F0F0',
borderRadius: 20,
flex: 1,
fontFamily: 'Poppins_400Regular',
height: 40,
marginRight: 10,
paddingHorizontal: 15,
},
inputContainer: {
alignItems: 'center',
backgroundColor: '#FFFFFF',
borderTopColor: '#E0E0E0',
borderTopWidth: 1,
flexDirection: 'row',
padding: 10,
},
loadingContainer: {
alignItems: 'center',
flex: 1,
justifyContent: 'center',
},
messageList: {
backgroundColor: '#F5F5F5',
flex: 1,
},
messageListContent: {
paddingVertical: 10, // Reduced vertical padding
paddingHorizontal: 15,
},
sendButton: {
backgroundColor: '#007AFF',
borderRadius: 20,
padding: 10,
},
typingAnimation: {
height: 40,
width: 80,
},
typingIndicator: {
bottom: 70,
left: 20,
position: 'absolute',
},
});
export default ChatScreen;