// src/screens/HomeScreen.tsx import React, { useEffect, useState, useCallback } from…
- User
// src/screens/HomeScreen.tsx import React, { useEffect, useState, useCallback } from 'react'; import { View, Text, 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(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} /> {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(), };
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 ( Tarihi Karakterler {loading ? ( // Optional: Replace with a different loading UI or remove entirely // For this example, we'll remove the loader ) : ( )} ); };
const styles = StyleSheet.create({ avatar: { borderRadius: 30, height: 60, marginRight: 15, width: 60, }, container: { backgroundColor: '#F5F5F5', flex: 1, paddingHorizontal: 15, }, figureDescription: { color: '#666', fontFamily: 'Poppins_400Regular', fontSize: 14, marginTop: 4, }, figureInfo: { flex: 1, }, figureItem: { alignItems: 'center', backgroundColor: '#FFFFFF', borderRadius: 12, elevation: 5, flexDirection: 'row', marginBottom: 15, marginHorizontal:3, padding: 20, shadowColor: "#000", shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.1, shadowRadius: 3.84, }, figureList: { paddingTop: 10, }, figureName: { color: '#333', fontFamily: 'Poppins_700Bold', fontSize: 18, }, header: { alignItems: 'center', borderBottomColor: '#E0E0E0', borderBottomWidth: 1, flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 20, }, infoButton: { padding: 5, }, loadingContainer: { alignItems: 'center', backgroundColor: '#F5F5F5', flex: 1, justifyContent: 'center', }, loadingPlaceholder: { flex: 1, // Optional styling for placeholder }, safeArea: { backgroundColor: '#F5F5F5', flex: 1, paddingTop: Platform.OS === 'android' ? RNStatusBar.currentHeight : 0, }, title: { color: '#333', fontFamily: 'Poppins_700Bold', fontSize: 28, }, });
export default HomeScreen; bu sayfa her açıldığında yeniden yükleniyor gibi. firebaseden bilgileri günde bir kez çeksin sonra asenkrona kaydetsin ve bir daha çekmesin. loading işaretleri kullanıcı deneyimini mahvediyo. bunu düzelt
- Assistant
To optimize your
HomeScreenso that it fetches historical figures from Firebase only once per day and caches the data locally usingAsyncStorage, follow these steps:-
Check Local Cache First: When the
HomeScreenmounts, first attempt to retrieve the data fromAsyncStorage. -
Validate Data Freshness: If cached data exists, check its timestamp to determine if it's older than a day.
-
Fetch Fresh Data if Needed: If no cached data exists or the data is stale (older than a day), fetch fresh data from Firebase, update the state, and store the new data along with the current timestamp in
AsyncStorage. -
Improve User Experience: Remove or adjust loading indicators to ensure a smoother user experience.
Below is the updated
HomeScreen.tsxwith these enhancements:// src/screens/HomeScreen.tsx import React, { useEffect, useState, useCallback } from 'react'; import { View, Text, 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 STORAGE_KEY_FIGURES = 'historical_figures'; const STORAGE_KEY_FIGURES_TIMESTAMP = 'historical_figures_timestamp'; const CACHE_DURATION = 24 * 60 * 60 * 1000; // 1 day in milliseconds const HomeScreen = () => { const navigation = useNavigation(); const [historicalFigures, setHistoricalFigures] = useState<HistoricalFigure[]>([]); const [loading, setLoading] = useState<boolean>(false); // Start with not loading useEffect(() => { const loadFigures = async () => { try { setLoading(true); const [cachedFigures, cachedTimestamp] = await Promise.all([ AsyncStorage.getItem(STORAGE_KEY_FIGURES), AsyncStorage.getItem(STORAGE_KEY_FIGURES_TIMESTAMP), ]); const now = Date.now(); const isCacheValid = cachedFigures && cachedTimestamp && (now - parseInt(cachedTimestamp, 10) < CACHE_DURATION); if (isCacheValid) { // Load from cache const figuresList: HistoricalFigure[] = JSON.parse(cachedFigures); setHistoricalFigures(figuresList); } else { // Fetch from Firebase await fetchFiguresFromFirebase(); } } catch (error) { console.error('Error loading figures:', error); Alert.alert("Hata", "Figürler yüklenirken bir hata oluştu."); } finally { setLoading(false); } }; const fetchFiguresFromFirebase = 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); // Save to AsyncStorage await Promise.all([ AsyncStorage.setItem(STORAGE_KEY_FIGURES, JSON.stringify(figuresList)), AsyncStorage.setItem(STORAGE_KEY_FIGURES_TIMESTAMP, now.toString()), ]); } catch (error) { console.error('Error fetching figures:', error); Alert.alert("Hata", "Figürler yüklenirken bir hata oluştu."); } }; loadFigures(); }, []); // 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}><Text>Tarihi Karakterler</Text></CustomText> <TouchableOpacity style={styles.infoButton} onPress={() => Alert.alert("Bilgi", "Tarihi karakterler listesi." /* Add more info if needed */)}> <Ionicons name="information-circle-outline" size={24} color="#007AFF" /> </TouchableOpacity> </View> <FlatList data={historicalFigures} renderItem={renderFigureItem} keyExtractor={keyExtractor} contentContainerStyle={styles.figureList} showsVerticalScrollIndicator={false} // Optionally, use refresh control to allow manual refresh // onRefresh={fetchFiguresFromFirebase} // refreshing={loading} /> </View> </SafeAreaView> ); }; const styles = StyleSheet.create({ avatar: { borderRadius: 30, height: 60, marginRight: 15, width: 60, }, container: { backgroundColor: '#F5F5F5', flex: 1, paddingHorizontal: 15, }, figureDescription: { color: '#666', fontFamily: 'Poppins_400Regular', fontSize: 14, marginTop: 4, }, figureInfo: { flex: 1, }, figureItem: { alignItems: 'center', backgroundColor: '#FFFFFF', borderRadius: 12, elevation: 5, flexDirection: 'row', marginBottom: 15, marginHorizontal: 3, padding: 20, shadowColor: "#000", shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.1, shadowRadius: 3.84, }, figureList: { paddingTop: 10, paddingBottom: 20, // Add some padding at the bottom }, figureName: { color: '#333', fontFamily: 'Poppins_700Bold', fontSize: 18, }, header: { alignItems: 'center', borderBottomColor: '#E0E0E0', borderBottomWidth: 1, flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 20, }, infoButton: { padding: 5, }, safeArea: { backgroundColor: '#F5F5F5', flex: 1, paddingTop: Platform.OS === 'android' ? RNStatusBar.currentHeight : 0, }, title: { color: '#333', fontFamily: 'Poppins_700Bold', fontSize: 28, }, }); export default HomeScreen;Detailed Explanation
-
Caching Strategy:
- Keys: Defined
STORAGE_KEY_FIGURESandSTORAGE_KEY_FIGURES_TIMESTAMPto store the figures and their fetch time. - Cache Duration: Set
CACHE_DURATIONto 24 hours (expressed in milliseconds). - Data Retrieval:
- Attempt to retrieve cached figures and their timestamp from
AsyncStorage. - Determine if cached data is still valid by comparing the current time with the stored timestamp.
- Attempt to retrieve cached figures and their timestamp from
- Data Fetching:
- If data is valid in cache, load it directly into the state.
- If not, fetch fresh data from Firebase, update the state, and store both the data and the current timestamp in
AsyncStorage.
- Keys: Defined
-
Managing
loadingState:- Initialized
loadingasfalsebecause the initial load will either fetch from cache or Firebase without showing a loader. - Show the
FlatListregardless ofloadingstate, removing any placeholder that might frustrate the user. - Optional Enhancements:
- You can integrate a pull-to-refresh mechanism by using
refreshingandonRefreshprops onFlatListto allow users to manually refresh the data if needed.
- You can integrate a pull-to-refresh mechanism by using
- Initialized
-
Removing Unnecessary Loading UI:
- Removed the conditional rendering based on
loadingand always display theFlatList. - By fetching data from
AsyncStoragefirst, the UI can populate quickly without waiting for network requests, enhancing user experience.
- Removed the conditional rendering based on
-
Additional Enhancements:
- Info Button: Added a
onPresshandler to the info button to provide more context or navigational actions when the info icon is pressed. - Styling: Minor adjustments to padding and layout to ensure the UI remains sharp and user-friendly.
- Info Button: Added a
Optional: Implement Pull-to-Refresh
If you'd like to offer users the ability to manually refresh the data, you can leverage the
refreshingandonRefreshprops provided byFlatList.Here's how to implement it:
-
Update State:
const [refreshing, setRefreshing] = useState<boolean>(false); -
Create Refresh Handler:
const handleRefresh = async () => { setRefreshing(true); await fetchFiguresFromFirebase(); setRefreshing(false); }; -
Pass Props to
FlatList:<FlatList data={historicalFigures} renderItem={renderFigureItem} keyExtractor={keyExtractor} contentContainerStyle={styles.figureList} showsVerticalScrollIndicator={false} refreshing={refreshing} onRefresh={handleRefresh} /> -
Ensure
fetchFiguresFromFirebaseis Accessible:Make sure the
fetchFiguresFromFirebasefunction is accessible within thehandleRefreshfunction. You may need to define it outside ofuseEffect.const fetchFiguresFromFirebase = 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); // Save to AsyncStorage const now = Date.now(); await Promise.all([ AsyncStorage.setItem(STORAGE_KEY_FIGURES, JSON.stringify(figuresList)), AsyncStorage.setItem(STORAGE_KEY_FIGURES_TIMESTAMP, now.toString()), ]); } catch (error) { console.error('Error fetching figures:', error); Alert.alert("Hata", "Figürler yüklenirken bir hata oluştu."); } };
By implementing pull-to-refresh, you offer users more control over data freshness without relying solely on the daily cache invalidation.
Handling Time Zones and Timestamps
Ensure that the timestamp stored and compared is consistent across different devices and time zones. Using UTC timestamps (
Date.now()) is generally reliable, but be cautious if your app heavily relies on date and time manipulations.Conclusion
By implementing this caching strategy, your
HomeScreenwill significantly reduce unnecessary network requests, enhance performance, and provide a smoother user experience. Users won’t experience delays due to loading indicators each time they navigate to theHomeScreen, especially when data hasn’t changed within the cache duration.Feel free to adjust the
CACHE_DURATIONor enhance the caching mechanism further based on your application's specific needs. -