Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

selamun aleyküm. burada giriş yapmış olan kullanıcı için profil resmi vs bir panelimiz…

  1. User

    selamun aleyküm. burada giriş yapmış olan kullanıcı için profil resmi vs bir panelimiz var. onun altına kullanıcının kalplediği öğeleri çekeceğiz. users/userid kısmından hearts { "storyid":"date", "storyid":"date", ........ şeklinde firebasede kayıtlı bilgiler mevcut. sonrasında bu çekilen storyid bilgilerini firebaseden stories/storyid şeklinde çekeceğiz. thumbnail bilgisi, kullanıcının dil seçeneğine göre locale değeri tr ise storytitleturkish, en ise storytitleenglish'i çekeceğiz firebaseden . bu dediğim özelliği müstakil başka bir sayfa olarak yapıp bu profilescreen sayfamıza import edeceğiz. şimdi kodları oluştur bakalım. kodları geriye gönderirken eksiksiz bir şekilde gönder.

    import React, { useEffect, useState, useCallback } from 'react'; import { Image, View, Text, StyleSheet, TouchableOpacity, Alert, ScrollView } from 'react-native'; import { useNavigation, useFocusEffect } from '@react-navigation/native'; import PropTypes from 'prop-types'; import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext'; import { auth, db } from '../utils/firebase'; import { doc, getDoc } from 'firebase/firestore'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { useVocabulary } from './VocabularyContext'; import { Ionicons } from '@expo/vector-icons';

    const ProfileScreen = ({ route }) => { const { theme, t, locale } = useThemeAndLanguage(); const navigation = useNavigation(); const { logout } = useVocabulary(); const [isLoggedIn, setIsLoggedIn] = useState(false); const [user, setUser] = useState(null); const [displayName1, setDisplayName1] = useState(''); const [catImageUrl, setCatImageUrl] = useState('https://cataas.com/cat?width=300&height=300'); const [coverImageUrl, setCoverImageUrl] = useState('https://picsum.photos/800/300');

    useEffect(() => { const unsubscribe = auth.onAuthStateChanged(fetchUserData); return () => unsubscribe(); }, []);

    useFocusEffect( useCallback(() => { const currentUser = auth.currentUser; if (currentUser) { fetchUserData(currentUser); } else if (route.params?.refresh) { fetchUserData(); } }, [route.params?.refresh]) );

    const fetchUserData = async (currentUser) => { if (currentUser) { setIsLoggedIn(true); setUser(currentUser);

      const userDoc = doc(db, 'users', currentUser.uid);
      const docSnap = await getDoc(userDoc);
    
      if (docSnap.exists()) {
        setDisplayName1(docSnap.data().displayName1 || '');
        await AsyncStorage.setItem('displayName1', docSnap.data().displayName1 || '');
      } else {
        console.log('No such document!');
      }
    } else {
      setIsLoggedIn(false);
      setUser(null);
      setDisplayName1('');
      await AsyncStorage.removeItem('displayName1');
    }
    

    };

    const handleLogout = async () => { try { await auth.signOut(); await AsyncStorage.clear(); await logout(); } catch (error) { Alert.alert('Error', error.message); } };

    const refreshImages = () => { const newCatImageUrl = https://cataas.com/cat?width=300&height=300&timestamp=${new Date().getTime()}; const newCoverImageUrl = https://picsum.photos/800/300?timestamp=${new Date().getTime()}; setCatImageUrl(newCatImageUrl); setCoverImageUrl(newCoverImageUrl); };

    return ( <ScrollView style={[styles.container, { backgroundColor: theme.backgroundColor }]}> {isLoggedIn && user ? ( <Image source={{ uri: coverImageUrl }} style={styles.coverImage} resizeMode="cover" /> <Image source={{ uri: catImageUrl }} style={styles.profileImage} resizeMode="cover" /> <Text style={[styles.username, { color: theme.textColor }]}> {displayName1 || 'Anonymous User'} <Text style={[styles.email, { color: theme.secondaryColor }]}> {user.email}

          <View style={styles.buttonContainer}>
            <View style={styles.row}>
              <TouchableOpacity
                style={[styles.button, { backgroundColor: theme.primaryColor }]}
                onPress={refreshImages}
              >
                <Ionicons name="refresh" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                <Text style={[styles.buttonText, { color: theme.textColor2 }]}>
                  {t('refreshImages')}
                </Text>
              </TouchableOpacity>
    
              <TouchableOpacity
                style={[styles.button, { backgroundColor: theme.primaryColor }]}
                onPress={() => navigation.navigate('Settings')}
              >
                <Ionicons name="settings-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('settingsNav')}</Text>
              </TouchableOpacity>
            </View>
    
            <View style={styles.row}>
              <TouchableOpacity
                style={[styles.button, { backgroundColor: theme.primaryColor }]}
                onPress={() => navigation.navigate('EditProfile')}
              >
                <Ionicons name="create-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('editProfile')}</Text>
              </TouchableOpacity>
    
              <TouchableOpacity
                style={[styles.button, { backgroundColor: theme.primaryColor }]}
                onPress={handleLogout}
              >
                <Ionicons name="log-out-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('logout')}</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      ) : (
        <View style={styles.buttonContainer}>
          <Image
            source={require('../../assets/kabe.jpg')}
            style={styles.image}
            resizeMode="cover"
          />
          <Text style={[styles.title, { color: theme.textColor }]}>{t('loginToYourAccount')}</Text>
         
          <TouchableOpacity
            style={[styles.button, { backgroundColor: theme.primaryColor }]}
            onPress={() => navigation.navigate('Login')}
          >
            <Ionicons name="log-in-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
            <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('login')}</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.button, { backgroundColor: theme.primaryColor }]}
            onPress={() => navigation.navigate('Register')}
          >
            <Ionicons name="person-add-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
            <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('register')}</Text>
          </TouchableOpacity>
        </View>
      )}
    </ScrollView>
    

    ); };

  2. Assistant

    Aleyküm selam! Kullanıcının kalplediği öğeleri göstermek için bağımsız bir HeartedStories bileşeni oluşturabiliriz ve ardından bu bileşeni ProfileScreen'e entegre edebiliriz. Aşağıda, bu işlemi adım adım gerçekleştiren eksiksiz kodları bulabilirsiniz.

    1. HeartedStories Bileşenini Oluşturma

    Öncelikle, HeartedStories.js adında yeni bir dosya oluşturun ve aşağıdaki kodları ekleyin. Bu bileşen, kullanıcının kalplediği hikayeleri Firebase'den çekecek ve ekranda görüntüleyecektir.

    // HeartedStories.js
    import React, { useEffect, useState } from 'react';
    import { View, Text, Image, StyleSheet, FlatList, TouchableOpacity, ActivityIndicator } from 'react-native';
    import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
    import { auth, db } from '../utils/firebase';
    import { doc, getDoc, collection, getDocs } from 'firebase/firestore';
    import { useNavigation } from '@react-navigation/native';
    import PropTypes from 'prop-types';
    
    const HeartedStories = () => {
      const { theme, locale, t } = useThemeAndLanguage();
      const navigation = useNavigation();
      const [heartedStories, setHeartedStories] = useState([]);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState(null);
    
      useEffect(() => {
        fetchHeartedStories();
      }, [locale]);
    
      const fetchHeartedStories = async () => {
        setLoading(true);
        setError(null);
        try {
          const currentUser = auth.currentUser;
          if (!currentUser) {
            setError(t('userNotLoggedIn'));
            setLoading(false);
            return;
          }
    
          // Referansını al users/userid/hearts
          const heartsDocRef = doc(db, 'users', currentUser.uid);
          const heartsDocSnap = await getDoc(heartsDocRef);
    
          if (!heartsDocSnap.exists()) {
            setError(t('noHeartedStories'));
            setLoading(false);
            return;
          }
    
          const heartsData = heartsDocSnap.data().hearts;
          if (!heartsData) {
            setError(t('noHeartedStories'));
            setLoading(false);
            return;
          }
    
          const storyIds = Object.keys(heartsData);
          if (storyIds.length === 0) {
            setError(t('noHeartedStories'));
            setLoading(false);
            return;
          }
    
          // Çoklu belgeleri almak için Firestore'da sorgu yapamıyoruz, bu yüzden tüm hikayeleri almak için Promise.all kullanacağız
          const storiesPromises = storyIds.map(async (storyId) => {
            const storyDocRef = doc(db, 'stories', storyId);
            const storyDocSnap = await getDoc(storyDocRef);
            if (storyDocSnap.exists()) {
              const storyData = storyDocSnap.data();
              return {
                id: storyId,
                thumbnail: storyData.thumbnail || '',
                title: locale === 'tr' ? storyData.storytitleturkish : storyData.storytitleenglish || 'Untitled Story',
                dateHearted: heartsData[storyId],
              };
            } else {
              return null;
            }
          });
    
          const storiesResults = await Promise.all(storiesPromises);
          const validStories = storiesResults.filter((story) => story !== null);
          setHeartedStories(validStories);
        } catch (err) {
          console.error('Error fetching hearted stories:', err);
          setError(t('errorFetchingStories'));
        } finally {
          setLoading(false);
        }
      };
    
      const renderStoryItem = ({ item }) => (
        <TouchableOpacity
          style={[styles.storyItem, { backgroundColor: theme.cardBackground }]}
          onPress={() => navigation.navigate('StoryDetail', { storyId: item.id })}
        >
          <Image source={{ uri: item.thumbnail }} style={styles.thumbnail} resizeMode="cover" />
          <View style={styles.storyInfo}>
            <Text style={[styles.storyTitle, { color: theme.textColor }]} numberOfLines={1}>
              {item.title}
            </Text>
            <Text style={[styles.dateHearted, { color: theme.secondaryTextColor }]}>
              {new Date(item.dateHearted).toLocaleDateString()}
            </Text>
          </View>
        </TouchableOpacity>
      );
    
      if (loading) {
        return (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color={theme.primaryColor} />
          </View>
        );
      }
    
      if (error) {
        return (
          <View style={styles.errorContainer}>
            <Text style={[styles.errorText, { color: theme.textColor }]}>{error}</Text>
          </View>
        );
      }
    
      return (
        <View style={styles.container}>
          <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>
      );
    };
    
    HeartedStories.propTypes = {
      // Eğer props kullanıyorsanız tanımlayın
    };
    
    const styles = StyleSheet.create({
      container: {
        marginTop: 20,
        paddingHorizontal: 16,
      },
      heading: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 10,
      },
      listContent: {
        paddingVertical: 10,
      },
      storyItem: {
        width: 150,
        marginRight: 15,
        borderRadius: 10,
        overflow: 'hidden',
        elevation: 2, // Android shadow
        shadowColor: '#000', // iOS shadow
        shadowOffset: { width: 0, height: 2 }, // iOS shadow
        shadowOpacity: 0.25, // iOS shadow
        shadowRadius: 3.84, // iOS shadow
      },
      thumbnail: {
        width: '100%',
        height: 100,
      },
      storyInfo: {
        padding: 10,
      },
      storyTitle: {
        fontSize: 16,
        fontWeight: '600',
      },
      dateHearted: {
        fontSize: 12,
        marginTop: 4,
      },
      loadingContainer: {
        padding: 20,
        alignItems: 'center',
      },
      errorContainer: {
        padding: 20,
        alignItems: 'center',
      },
      errorText: {
        fontSize: 16,
      },
    });
    
    export default HeartedStories;
    

    2. ProfileScreen'e HeartedStories Bileşenini Entegre Etme

    Şimdi HeartedStories bileşenini ProfileScreen'e ekleyerek kullanıcı profilinde kalplediği hikayeleri göstereceğiz. Aşağıda güncellenmiş ProfileScreen kodunu bulabilirsiniz.

    // ProfileScreen.js
    import React, { useEffect, useState, useCallback } from 'react';
    import { Image, View, Text, StyleSheet, TouchableOpacity, Alert, ScrollView } from 'react-native';
    import { useNavigation, useFocusEffect } from '@react-navigation/native';
    import PropTypes from 'prop-types';
    import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
    import { auth, db } from '../utils/firebase';
    import { doc, getDoc } from 'firebase/firestore';
    import AsyncStorage from '@react-native-async-storage/async-storage';
    import { useVocabulary } from './VocabularyContext';
    import { Ionicons } from '@expo/vector-icons';
    import HeartedStories from './HeartedStories'; // Import ettiğiniz yeni bileşen
    
    const ProfileScreen = ({ route }) => {
      const { theme, t, locale } = useThemeAndLanguage();
      const navigation = useNavigation();
      const { logout } = useVocabulary();
      const [isLoggedIn, setIsLoggedIn] = useState(false);
      const [user, setUser] = useState(null);
      const [displayName1, setDisplayName1] = useState('');
      const [catImageUrl, setCatImageUrl] = useState('https://cataas.com/cat?width=300&height=300');
      const [coverImageUrl, setCoverImageUrl] = useState('https://picsum.photos/800/300');
    
      useEffect(() => {
        const unsubscribe = auth.onAuthStateChanged(fetchUserData);
        return () => unsubscribe();
      }, []);
    
      useFocusEffect(
        useCallback(() => {
          const currentUser = auth.currentUser;
          if (currentUser) {
            fetchUserData(currentUser);
          } else if (route.params?.refresh) {
            fetchUserData();
          }
        }, [route.params?.refresh])
      );
    
      const fetchUserData = async (currentUser) => {
        if (currentUser) {
          setIsLoggedIn(true);
          setUser(currentUser);
    
          const userDoc = doc(db, 'users', currentUser.uid);
          const docSnap = await getDoc(userDoc);
    
          if (docSnap.exists()) {
            setDisplayName1(docSnap.data().displayName1 || '');
            await AsyncStorage.setItem('displayName1', docSnap.data().displayName1 || '');
          } else {
            console.log('No such document!');
          }
        } else {
          setIsLoggedIn(false);
          setUser(null);
          setDisplayName1('');
          await AsyncStorage.removeItem('displayName1');
        }
      };
    
      const handleLogout = async () => {
        try {
          await auth.signOut();
          await AsyncStorage.clear();
          await logout();
        } catch (error) {
          Alert.alert('Error', error.message);
        }
      };
    
      const refreshImages = () => {
        const newCatImageUrl = `https://cataas.com/cat?width=300&height=300&timestamp=${new Date().getTime()}`;
        const newCoverImageUrl = `https://picsum.photos/800/300?timestamp=${new Date().getTime()}`;
        setCatImageUrl(newCatImageUrl);
        setCoverImageUrl(newCoverImageUrl);
      };
    
      return (
        <ScrollView style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
          {isLoggedIn && user ? (
            <View>
              <View style={styles.coverImageContainer}>
                <Image
                  source={{ uri: coverImageUrl }}
                  style={styles.coverImage}
                  resizeMode="cover"
                />
              </View>
              <View style={styles.profileInfo}>
                <Image
                  source={{ uri: catImageUrl }}
                  style={styles.profileImage}
                  resizeMode="cover"
                />
                <Text style={[styles.username, { color: theme.textColor }]}>
                  {displayName1 || 'Anonymous User'}
                </Text>
                <Text style={[styles.email, { color: theme.secondaryColor }]}>
                  {user.email}
                </Text>
              </View>
    
              <View style={styles.buttonContainer}>
                <View style={styles.row}>
                  <TouchableOpacity
                    style={[styles.button, { backgroundColor: theme.primaryColor }]}
                    onPress={refreshImages}
                  >
                    <Ionicons name="refresh" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                    <Text style={[styles.buttonText, { color: theme.textColor2 }]}>
                      {t('refreshImages')}
                    </Text>
                  </TouchableOpacity>
    
                  <TouchableOpacity
                    style={[styles.button, { backgroundColor: theme.primaryColor }]}
                    onPress={() => navigation.navigate('Settings')}
                  >
                    <Ionicons name="settings-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                    <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('settingsNav')}</Text>
                  </TouchableOpacity>
                </View>
    
                <View style={styles.row}>
                  <TouchableOpacity
                    style={[styles.button, { backgroundColor: theme.primaryColor }]}
                    onPress={() => navigation.navigate('EditProfile')}
                  >
                    <Ionicons name="create-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                    <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('editProfile')}</Text>
                  </TouchableOpacity>
    
                  <TouchableOpacity
                    style={[styles.button, { backgroundColor: theme.primaryColor }]}
                    onPress={handleLogout}
                  >
                    <Ionicons name="log-out-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                    <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('logout')}</Text>
                  </TouchableOpacity>
                </View>
              </View>
    
              {/* HeartedStories Bileşenini Burada Kullanıyoruz */}
              <HeartedStories />
            </View>
          ) : (
            <View style={styles.buttonContainer}>
              <Image
                source={require('../../assets/kabe.jpg')}
                style={styles.image}
                resizeMode="cover"
              />
              <Text style={[styles.title, { color: theme.textColor }]}>{t('loginToYourAccount')}</Text>
             
              <TouchableOpacity
                style={[styles.button, { backgroundColor: theme.primaryColor }]}
                onPress={() => navigation.navigate('Login')}
              >
                <Ionicons name="log-in-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('login')}</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.button, { backgroundColor: theme.primaryColor }]}
                onPress={() => navigation.navigate('Register')}
              >
                <Ionicons name="person-add-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('register')}</Text>
              </TouchableOpacity>
            </View>
          )}
        </ScrollView>
      );
    };
    
    ProfileScreen.propTypes = {
      route: PropTypes.object.isRequired,
    };
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
      },
      coverImageContainer: {
        width: '100%',
        height: 200,
      },
      coverImage: {
        width: '100%',
        height: '100%',
      },
      profileInfo: {
        alignItems: 'center',
        marginTop: -50,
        paddingVertical: 10,
      },
      profileImage: {
        width: 100,
        height: 100,
        borderRadius: 50,
        borderWidth: 3,
        borderColor: '#fff',
      },
      username: {
        fontSize: 20,
        fontWeight: 'bold',
        marginTop: 10,
      },
      email: {
        fontSize: 14,
        color: '#888',
        marginTop: 5,
      },
      buttonContainer: {
        paddingHorizontal: 16,
        paddingVertical: 20,
      },
      row: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginBottom: 15,
      },
      button: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 10,
        paddingHorizontal: 15,
        borderRadius: 8,
        flex: 1,
        marginHorizontal: 5,
      },
      buttonIcon: {
        marginRight: 8,
      },
      buttonText: {
        fontSize: 16,
      },
      image: {
        width: '100%',
        height: 250,
        borderRadius: 10,
        marginBottom: 20,
      },
      title: {
        fontSize: 18,
        textAlign: 'center',
        marginBottom: 20,
      },
    });
    
    export default ProfileScreen;
    

    3. Çeviriler (i18n) İçin Gerekli Metinleri Ekleyin

    HeartedStories bileşeninde kullanılan bazı çeviri anahtarları (t('...')) bulunmaktadır. Bu anahtarların i18n çeviri dosyalarınıza eklenmesi gerekmektedir. Aşağıda, eklemeniz gereken çeviri anahtarlarının örneklerini bulabilirsiniz.

    Örnek Türkçe (tr) Çeviriler:

    {
      "heartedStories": "Kalplediğin Hikayeler",
      "userNotLoggedIn": "Kullanıcı giriş yapmamış.",
      "noHeartedStories": "Kalplediğin hikaye bulunmuyor.",
      "errorFetchingStories": "Hikayeler alınırken bir hata oluştu.",
      "refreshImages": "Resimleri Yenile",
      "settingsNav": "Ayarlar",
      "editProfile": "Profil Düzenle",
      "logout": "Çıkış Yap",
      "loginToYourAccount": "Hesabınıza Giriş Yapın",
      "login": "Giriş Yap",
      "register": "Kayıt Ol"
    }
    

    Örnek İngilizce (en) Çeviriler:

    {
      "heartedStories": "Your Hearted Stories",
      "userNotLoggedIn": "User is not logged in.",
      "noHeartedStories": "No hearted stories found.",
      "errorFetchingStories": "An error occurred while fetching stories.",
      "refreshImages": "Refresh Images",
      "settingsNav": "Settings",
      "editProfile": "Edit Profile",
      "logout": "Logout",
      "loginToYourAccount": "Login to Your Account",
      "login": "Login",
      "register": "Register"
    }
    

    Bu çevirileri kendi projenizin i18n yapılandırmasına göre uyarlayın.

    4. Navigasyon için StoryDetail Sayfasını Ekleyin

    HeartedStories bileşeninde, kullanıcı bir hikayeye dokunduğunda StoryDetail sayfasına yönlendirme yapılıyor. Bu nedenle, StoryDetail sayfasının mevcut olduğundan ve doğru şekilde yapılandırıldığından emin olun. Örneğin:

    // StoryDetail.js
    import React, { useEffect, useState } from 'react';
    import { View, Text, Image, StyleSheet, ActivityIndicator, ScrollView } from 'react-native';
    import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
    import { db } from '../utils/firebase';
    import { doc, getDoc } from 'firebase/firestore';
    import PropTypes from 'prop-types';
    
    const StoryDetail = ({ route }) => {
      const { theme, locale, t } = useThemeAndLanguage();
      const { storyId } = route.params;
      const [story, setStory] = useState(null);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState(null);
    
      useEffect(() => {
        fetchStory();
      }, [storyId, locale]);
    
      const fetchStory = async () => {
        setLoading(true);
        setError(null);
        try {
          const storyDocRef = doc(db, 'stories', storyId);
          const storyDocSnap = await getDoc(storyDocRef);
          if (storyDocSnap.exists()) {
            const storyData = storyDocSnap.data();
            setStory({
              id: storyId,
              title: locale === 'tr' ? storyData.storytitleturkish : storyData.storytitleenglish || 'Untitled Story',
              content: storyData.content || '',
              image: storyData.thumbnail || '',
            });
          } else {
            setError(t('storyNotFound'));
          }
        } catch (err) {
          console.error('Error fetching story:', err);
          setError(t('errorFetchingStories'));
        } finally {
          setLoading(false);
        }
      };
    
      if (loading) {
        return (
          <View style={detailStyles.loadingContainer}>
            <ActivityIndicator size="large" color={theme.primaryColor} />
          </View>
        );
      }
    
      if (error) {
        return (
          <View style={detailStyles.errorContainer}>
            <Text style={[detailStyles.errorText, { color: theme.textColor }]}>{error}</Text>
          </View>
        );
      }
    
      return (
        <ScrollView style={[detailStyles.container, { backgroundColor: theme.backgroundColor }]}>
          {story && (
            <View>
              <Image source={{ uri: story.image }} style={detailStyles.image} resizeMode="cover" />
              <Text style={[detailStyles.title, { color: theme.textColor }]}>{story.title}</Text>
              <Text style={[detailStyles.content, { color: theme.textColor }]}>{story.content}</Text>
            </View>
          )}
        </ScrollView>
      );
    };
    
    StoryDetail.propTypes = {
      route: PropTypes.object.isRequired,
    };
    
    const detailStyles = StyleSheet.create({
      container: {
        flex: 1,
        padding: 16,
      },
      loadingContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      },
      errorContainer: {
        padding: 20,
        alignItems: 'center',
      },
      errorText: {
        fontSize: 16,
      },
      image: {
        width: '100%',
        height: 200,
        borderRadius: 10,
        marginBottom: 15,
      },
      title: {
        fontSize: 22,
        fontWeight: 'bold',
        marginBottom: 10,
      },
      content: {
        fontSize: 16,
        lineHeight: 24,
      },
    });
    
    export default StoryDetail;
    

    i18n Çevirileri için:

    {
      "storyNotFound": "Hikaye bulunamadı.",
      "errorFetchingStories": "Hikayeler alınırken bir hata oluştu."
    }
    

    5. Navigasyon Yapılandırmasını Güncelleyin

    react-navigation kullanıyorsanız, navigasyon yığınınıza (stack) StoryDetail sayfasını eklemeniz gerekmektedir. Örneğin:

    // App.js veya navigasyon dosyanız
    import React from 'react';
    import { NavigationContainer } from '@react-navigation/native';
    import { createStackNavigator } from '@react-navigation/stack';
    
    import ProfileScreen from './screens/ProfileScreen';
    import StoryDetail from './screens/StoryDetail';
    // Diğer ekranlar...
    
    const Stack = createStackNavigator();
    
    const App = () => {
      return (
        <NavigationContainer>
          <Stack.Navigator initialRouteName="Profile">
            {/* Diğer ekranlarınız */}
            <Stack.Screen name="Profile" component={ProfileScreen} />
            <Stack.Screen name="StoryDetail" component={StoryDetail} options={{ title: 'Story Details' }} />
            {/* Diğer ekranlar */}
          </Stack.Navigator>
        </NavigationContainer>
      );
    };
    
    export default App;
    

    6. Firebase Yapılandırmasını Kontrol Edin

    • Firestore Kuralları: Kullanıcıların yalnızca kendi hearts verilerini okuyabileceğinden emin olun. Örneğin:
    // Firestore security rules example
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{userId} {
          allow read, write: if request.auth != null && request.auth.uid == userId;
          
          match /hearts/{heartId} {
            allow read, write: if request.auth != null && request.auth.uid == userId;
          }
        }
    
        match /stories/{storyId} {
          allow read: if true; // Hikayeleri herkese açık yapmak isteyebilirsiniz
          // Daha spesifik kurallar ekleyebilirsiniz
        }
      }
    }
    
    • Veri Yapısı: Firestore'da users koleksiyonunuzda her kullanıcının hearts alanının şu yapıda olduğundan emin olun:
    "hearts": {
      "storyId1": "2023-10-01T12:34:56Z",
      "storyId2": "2023-10-02T08:22:10Z",
      // Diğer hikayeler...
    }
    

    7. Özet

    Bu adımları takip ederek, kullanıcının kalplediği hikayeleri profil ekranında görüntüleyen bağımsız bir bileşen oluşturmuş oldunuz. Bu bileşen, ProfileScreen içinde kolayca kullanılabilir ve projenizin modülerliğini artırır. Gerektiğinde stil ve işlevselliği özelleştirmek için HeartedStories bileşenini düzenleyebilirsiniz.

    Eğer herhangi bir sorunla karşılaşırsanız veya ek yardıma ihtiyacınız olursa, lütfen sormaktan çekinmeyin!