1

I stored some data on firebase collection, through the following code i am able to get that data on console but i am unable to render it on my website front-end. I am new to firebase can somebody please help me correct my code..

import React, { useState, useEffect} from 'react'
import "./Feed.css"
import MessageSender from './MessageSender'
import Post from './Post'
import StoryReel from "./StoryReel"
import db from "./firebase"
import { query, getDocs, onSnapshot, collection } from 'firebase/firestore';

function Feed() {
  const colRef = collection(db, 'posts')
  const posts =[]

onSnapshot(colRef, (snapshot) => {
      snapshot.docs.map((doc) =>{            
        posts.push({data:doc.data(), id: doc.id})
      })
      console.log(posts)
     } )    


  return (
    <div className="Feed">
        <StoryReel />
        <MessageSender />

      {posts.map((post) => {
          <Post
            key={post.id}
            profilePic={post.data.profilePic}
            message={post.data.message}
            timestamp={post.data.timestamp}
            username={post.data.username}
            image={post.data.image}
          />
        })}
       
    </div>
  )
}

export default Feed
  • please, no pictures of text ... delete the picture ... add the text – jsotola Sep 21 '22 at 17:06
  • 1
    Please don't post screenshots of your code, or other textual content. Instead post the actual text, and use the formatting tools of Stack Overflow to mark it up. Also see: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) – Frank van Puffelen Sep 21 '22 at 17:09

1 Answers1

0

Since you're using React, you can use useState to re-render whenever posts changes.

const [posts, setPosts] = useState([])

onSnapshot(colRef, (snapshot) => {
      const tempPosts = []
      snapshot.docs.map((doc) =>{            
        tempPosts.push({data:doc.data(), id: doc.id})
      })
      console.log(tempPosts)
      setPosts(tempPosts)
     } )  
Jim P
  • 87
  • 11
  • Separately, when using snapshot listeners and React, you need to dispose of the listener when your component unmounts. You can do so with a useEffect -- see https://stackoverflow.com/questions/70214878/react-usestate-and-firebase-onsnapshot – Jim P Sep 21 '22 at 21:44
  • I tried the code you posted above but still i am facing the same issue. – Kundan Agrawal Sep 22 '22 at 13:06