The issue you're encountering stems from inconsistent data within the hearts field of your Firestore users documents. Specifically, some entries in the hearts object are set to numeric values (1) or null instead of ISO date strings. This inconsistency disrupts the sorting mechanism in your HeartedStories component, leading to unexpected ordering of stories.
To resolve this, we'll take the following steps:
-
Ensure Consistent Data Structure:
- Data Normalization: Ensure that the
hearts field only contains ISO date strings when a story is hearted and removes the entry or sets it to null when unhearted.
- Data Migration: Correct existing inconsistent data in Firestore to align with the expected structure.
-
Refactor the HeartContext to Prevent Future Inconsistencies:
- Ensure that only valid date strings are set when hearting a story.
- Prevent the accidental setting of non-date values like
1.
-
Enhance the HeartedStories Component for Robustness:
- Handle cases where
likedAt might not be a valid date.
- Provide fallback mechanisms to ensure the component remains functional even if some data entries are malformed.
-
Implement Error Handling and Logging:
- Add comprehensive error handling to catch and log potential issues during data fetching and updating.
Let's go through each step in detail.
1. Ensure Consistent Data Structure
a. Data Normalization & Migration
Before implementing code changes, it's crucial to clean up the existing data in your Firestore to ensure consistency. You can use Firebase's Cloud Functions or a script using Firebase Admin SDK to iterate through user documents and correct the hearts field.
Here's an example script using Firebase Admin SDK to clean up the hearts field:
// This script should be run in a secure environment with Firebase Admin SDK initialized.
const admin = require('firebase-admin');
// Initialize Firebase Admin SDK
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
const db = admin.firestore();
const cleanUserHearts = async () => {
const usersSnapshot = await db.collection('users').get();
const batch = db.batch();
usersSnapshot.forEach((userDoc) => {
const hearts = userDoc.get('hearts');
if (hearts && typeof hearts === 'object') {
let updated = false;
const newHearts = { ...hearts };
Object.keys(newHearts).forEach((storyId) => {
const value = newHearts[storyId];
if (typeof value !== 'string') {
// Remove invalid heart entries
delete newHearts[storyId];
updated = true;
}
});
if (updated) {
batch.update(userDoc.ref, { hearts: newHearts });
}
}
});
// Commit the batch
await batch.commit();
console.log('Hearts cleaned successfully.');
};
cleanUserHearts().catch((error) => {
console.error('Error cleaning hearts:', error);
});
Important: Ensure you have the necessary permissions and backups before running such scripts to prevent data loss.
b. Future-Proofing Data Structure
Ensure that only valid date strings are written to the hearts field in your application code. This involves refining the HeartContext and ToggleHeartButton components.
2. Refactor the HeartContext to Prevent Future Inconsistencies
We'll enhance the HeartContext to ensure that only ISO date strings are set when a user hearts a story. Additionally, we'll add validation to prevent accidental setting of invalid values.
Updated HeartContext.js:
// heartcontext.js
import React, { createContext, useState, useEffect } from 'react';
import { db, auth } from '../utils/firebase';
import { doc, getDoc, updateDoc, increment, collection, getDocs } from 'firebase/firestore';
export const HeartContext = createContext();
export const HeartProvider = ({ children }) => {
const [heartsCounts, setHeartsCounts] = useState({});
const [userHearts, setUserHearts] = useState({});
// Fetch user's hearted stories
useEffect(() => {
const fetchUserHearts = async () => {
if (auth.currentUser) {
const userRef = doc(db, 'users', auth.currentUser.uid);
try {
const userDoc = await getDoc(userRef);
if (userDoc.exists()) {
const hearts = userDoc.data().hearts || {};
// Filter out any invalid heart entries
const validHearts = Object.entries(hearts).reduce((acc, [key, value]) => {
if (typeof value === 'string' && !isNaN(Date.parse(value))) {
acc[key] = value;
}
return acc;
}, {});
setUserHearts(validHearts);
}
} catch (error) {
console.error('Error fetching user hearts:', error);
}
} else {
setUserHearts({});
}
};
fetchUserHearts();
}, [auth.currentUser]);
// Fetch all stories' heart counts
useEffect(() => {
const fetchHeartsCounts = async () => {
try {
const storiesSnapshot = await getDocs(collection(db, 'stories'));
const counts = {};
storiesSnapshot.forEach((doc) => {
counts[doc.id] = doc.data().hearts || 0;
});
setHeartsCounts(counts);
} catch (error) {
console.error('Error fetching hearts counts:', error);
}
};
fetchHeartsCounts();
// Optional: Listen for real-time updates
// const unsubscribe = onSnapshot(collection(db, 'stories'), (snapshot) => {
// const counts = {};
// snapshot.forEach((doc) => {
// counts[doc.id] = doc.data().hearts || 0;
// });
// setHeartsCounts(counts);
// });
// return () => unsubscribe();
}, []);
const toggleHeart = async (storyId) => {
if (!auth.currentUser) return;
const userRef = doc(db, 'users', auth.currentUser.uid);
const storyRef = doc(db, 'stories', storyId);
const isHearted = !!userHearts[storyId];
try {
if (isHearted) {
// Remove heart
await updateDoc(userRef, { [`hearts.${storyId}`]: null });
await updateDoc(storyRef, { hearts: increment(-1) });
setUserHearts((prev) => {
const updated = { ...prev };
delete updated[storyId];
return updated;
});
setHeartsCounts((prev) => ({
...prev,
[storyId]: (prev[storyId] || 1) - 1,
}));
} else {
// Add heart with current timestamp
const timestamp = new Date().toISOString();
await updateDoc(userRef, { [`hearts.${storyId}`]: timestamp });
await updateDoc(storyRef, { hearts: increment(1) });
setUserHearts((prev) => ({
...prev,
[storyId]: timestamp,
}));
setHeartsCounts((prev) => ({
...prev,
[storyId]: (prev[storyId] || 0) + 1,
}));
}
} catch (error) {
console.error('Error toggling heart:', error);
// Optionally, implement rollback logic here
}
};
return (
<HeartContext.Provider value={{ heartsCounts, userHearts, toggleHeart }}>
{children}
</HeartContext.Provider>
);
};
Key Enhancements:
-
Validation: When fetching userHearts, we filter out any entries that aren't valid ISO date strings to prevent malformed data from affecting the functionality.
-
Robust Error Handling: Added try-catch blocks to handle potential errors during data fetching.
-
リアルタイム تحديثات (Optional): Consider uncommenting and using real-time listeners (onSnapshot) if you desire real-time updates without manual refreshes.
3. Enhance the HeartedStories Component for Robustness
We'll update the HeartedStories component to handle cases where likedAt might not be a valid date string and ensure proper sorting.
Updated HeartedStories.js:
// HeartedStories.js
import React, { useEffect, useState, useCallback, useContext } from 'react';
import {
View,
Text,
Image,
StyleSheet,
FlatList,
TouchableOpacity,
ActivityIndicator,
} from 'react-native';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { db } from '../utils/firebase';
import { doc, getDoc } from 'firebase/firestore';
import { useNavigation } from '@react-navigation/native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { HeartContext } from './HeartContext';
const HeartedStories = () => {
const { theme, locale, t } = useThemeAndLanguage();
const navigation = useNavigation();
const { userHearts, heartsCounts } = useContext(HeartContext);
const [heartedStories, setHeartedStories] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const fetchHeartedStories = useCallback(async () => {
setLoading(true);
setError(null);
try {
const storyIds = Object.keys(userHearts);
if (storyIds.length === 0) {
setError(t('noHeartedStories'));
setHeartedStories([]);
setLoading(false);
return;
}
const storiesPromises = storyIds.map(async (storyId) => {
const storyDocRef = doc(db, 'stories', storyId);
const storyDocSnap = await getDoc(storyDocRef);
if (storyDocSnap.exists()) {
const storyData = storyDocSnap.data();
// Validate 'likedAt' as a valid date
const likedAt = userHearts[storyId];
const isValidDate = typeof likedAt === 'string' && !isNaN(Date.parse(likedAt));
if (!isValidDate) {
console.warn(`Invalid likedAt for storyId ${storyId}:`, likedAt);
return null;
}
return {
id: storyId,
thumbnail: storyData.thumbnail || '',
storytitlearabic: storyData.storytitlearabic || '',
title:
locale === 'tr'
? storyData.storytitleturkish
: storyData.storytitleenglish || 'Untitled Story',
hearts: heartsCounts[storyId] || 0,
likedAt, // We already verified this is a valid date string
};
}
return null;
});
const storiesResults = await Promise.all(storiesPromises);
const validStories = storiesResults.filter((story) => story !== null);
if (validStories.length === 0) {
setError(t('noHeartedStories'));
setHeartedStories([]);
setLoading(false);
return;
}
// Sort by 'likedAt' descending (most recent first)
const sortedValidStories = validStories.sort(
(a, b) => new Date(b.likedAt) - new Date(a.likedAt)
);
setHeartedStories(sortedValidStories);
} catch (err) {
console.error('Error fetching hearted stories:', err);
setError(t('errorFetchingStories'));
} finally {
setLoading(false);
}
}, [userHearts, heartsCounts, locale, t]);
useEffect(() => {
fetchHeartedStories();
}, [fetchHeartedStories]);
const renderStoryItem = useCallback(
({ item }) => (
<TouchableOpacity
style={[styles.card, { backgroundColor: theme.cardBackground }]}
onPress={() => navigation.navigate('ReadStoryScreen', { storyId: item.id })}
>
<Image
source={{ uri: item.thumbnail }}
style={styles.thumbnail}
resizeMode="cover"
/>
<View style={styles.textContainer}>
<Text
style={[styles.title, { color: theme.textColor }]}
numberOfLines={1}
>
{item.title}
</Text>
<Text
style={[
styles.titleArabic,
{ color: theme.secondaryTextColor },
]}
numberOfLines={1}
>
{item.storytitlearabic}
</Text>
<View style={styles.heartContainer}>
<Ionicons
name={'heart'}
color={'red'}
size={20}
/>
<Text style={{ marginLeft: 4, color: theme.textColor }}>
{item.hearts}
</Text>
</View>
</View>
</TouchableOpacity>
),
[navigation, theme]
);
if (loading) {
return (
<View style={[styles.loadingContainer, { backgroundColor: theme.backgroundColor }]}>
<ActivityIndicator size="large" color={theme.primaryColor} />
</View>
);
}
if (error) {
return (
<View style={[styles.errorContainer, { backgroundColor: theme.backgroundColor }]}>
<Text style={[styles.errorText, { color: theme.textColor }]}>{error}</Text>
</View>
);
}
return (
<View style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
<Text style={[styles.heading, { color: theme.textColor }]}>{t('heartedStories')}</Text>
<FlatList
data={heartedStories}
keyExtractor={(item) => item.id}
renderItem={renderStoryItem}
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.listContent}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
paddingHorizontal: 16,
flex: 1,
},
heading: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 10,
},
listContent: {
paddingVertical: 10,
},
card: {
width: 160,
marginRight: 8,
borderRadius: 12,
overflow: 'hidden',
borderWidth: 1,
borderColor: '#ddd', // Softer border
},
thumbnail: {
width: '100%',
height: 100,
},
textContainer: {
padding: 10,
justifyContent: 'space-between',
flex: 1,
},
title: {
fontSize: 16,
fontWeight: '600',
textAlign: 'center',
},
titleArabic: {
fontSize: 14,
fontStyle: 'italic',
marginTop: 4,
textAlign: 'center',
},
heartContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginTop: 5,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
errorContainer: {
padding: 20,
alignItems: 'center',
flex: 1,
justifyContent: 'center',
},
errorText: {
fontSize: 16,
textAlign: 'center',
},
});
export default HeartedStories;
Key Enhancements:
-
Validation of likedAt: Before including a story in the heartedStories list, we verify that the likedAt field is a valid date string. If it's invalid, we exclude the story and log a warning.
-
Enhanced Rendering: Updated the renderStoryItem to display the number of hearts next to the heart icon for better user feedback.
-
User Experience Improvements:
- Added
marginBottom to the heading for better spacing.
- Styled the error and loading containers to be more consistent with the theme.
4. Update the ToggleHeartButton Component
Ensure that the ToggleHeartButton accurately reflects the hearted state and prevents inconsistencies.
Updated ToggleHeartButton.js:
// ToggleHeartButton.js
import React, { useContext } from 'react';
import { TouchableOpacity, Text } from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { useNavigation } from '@react-navigation/native';
import { HeartContext } from './HeartContext';
import { auth } from '../utils/firebase';
const ToggleHeartButton = ({ storyId }) => {
const { userHearts, toggleHeart, heartsCounts } = useContext(HeartContext);
const navigation = useNavigation();
const isHearted = !!userHearts[storyId];
const handleToggleHeart = () => {
if (!auth.currentUser) {
navigation.navigate('Login');
return;
}
toggleHeart(storyId);
};
return (
<TouchableOpacity onPress={handleToggleHeart} style={{ flexDirection: 'row', alignItems: 'center' }}>
<Ionicons
name={isHearted ? 'heart' : 'heart-outline'}
color={isHearted ? 'red' : 'black'}
size={24}
/>
{/* Optionally, display the number of hearts */}
<Text style={{ marginLeft: 4, color: isHearted ? 'red' : 'black' }}>
{heartsCounts[storyId] || 0}
</Text>
</TouchableOpacity>
);
};
export default ToggleHeartButton;
Key Enhancements:
-
User Feedback: Displays the number of hearts next to the heart icon, providing immediate feedback to the user.
-
Consistent Styling: Ensures the text color aligns with the heart's color for better visual consistency.
5. Additional Recommendations
a. Real-time Updates (Optional)
To provide real-time updates to heart counts and user hearts without needing to refresh, consider integrating Firestore's real-time listeners (onSnapshot). This can enhance the user experience by immediately reflecting changes made by the user or other users.
b. Optimistic UI Updates
For a more responsive UI, you can implement optimistic updates where the UI reflects changes immediately upon user interaction, without waiting for Firestore operations to complete. If an error occurs during the update, revert the UI changes and notify the user.
c. Localization and Theme Handling
Ensure that all text strings like 'heartedStories', 'noHeartedStories', and 'errorFetchingStories' are correctly defined in your localization files for proper translation.
Summary
By ensuring data consistency within Firestore, enhancing context and component logic to handle edge cases, and implementing robust error handling, your HeartedStories feature should function as intended. Regularly validate and sanitize data to prevent future inconsistencies and provide a seamless user experience.
If you continue to encounter issues after implementing these changes, consider adding more detailed logs and debugging steps to trace the problem further.