Home > Back-end >  Adding Realtime firebase data with useState to a flatlist
Adding Realtime firebase data with useState to a flatlist

Time:02-06

I want to take this data and display it in a flatlist. I tried the way described below, but it wont show me anything in the flatlist. How would i be able to solve this problem?

Code for fetching data

useEffect(() => {
    refComment.once('value').then(snapshot=>{

        var li=[]

        
          snapshot.forEach((child) => {
            
            li.push({
            //    avatarIcon : child.val().avatarIcon,
            //    commentText : child.val().commentText,
            //    name : child.val().name,
            //   time : child.val().time,
            //   id : child.key
                key:child.key,
                comment:child.val()
            }   
            )

          }
          
      )
       setcommentData(li)
       console.log(li);
      })

   
 } , []);

code for my flatlist

<Card>
  <View style={styles.answerDetailsView}>
  <View style={styles.allContentView}>
      <Text style={styles.allContentText}>Tüm yorumlar</Text>
    </View>
    <Divider/>
    
    <FlatList
    data={commentData}
    keyExtractor={(item)=>item.key}
    renderItem={({item,index})=>{
       return(
        <View 
        index={index}
        style={styles.contentView}>
        <View style={styles.commentatorDetailView}>
            <View style={styles.commentatorAvatarView}>
               <Avatar.Icon
               size={30}
               icon={item.avatarIcon}
               />
            </View>
            <View style={styles.commentatorNameAndTimeView}>
               <Text>{item.name}</Text>
               <Text>{item.time}</Text> 
            </View>
            <View style={styles.commentatorLikeView}>
                <TouchableOpacity>
                    <Icon
                    name='thumbs-up'
                    />
                </TouchableOpacity>
            </View>
        </View>
        <View style={styles.contentTextView}>
        <Text style={styles.contentText}>
            {item.commentText}
        </Text>
        </View>
      </View>
       ) 
    }}
   
    />
    
    
  </View>
  </Card>

And RealTime firebase screen

enter image description here

my mobile screenshot

enter image description here

CodePudding user response:

Try to refactor logic to fetch comments as below:

function getComments() {
  const commentsRef = firebase.database().ref("comments");

  commentsRef.on("value", (snapshot) => {
    if (snapshot.val()) {
      const data = snapshot.val();
      const comments = Object.values(data) || [];

      setcommentData(comments);
    }
  });
}

useEffect(() => {
  getComments();
}, []);





  •  Tags:  
  • Related