I am trying to display all the 'posts' from my database in a different divs. The code does get the posts and pushes them in the posts array. Here comes the problem. The posts.forEach method should run but it does not.It won't push the div's in the allposts array. Even the console.log wouldn't run. At the end the allposts returns an empty array. Anyone knows what could be the issue? I can't figure it out.
const db = getFirestore();
const colRef = collection(db, 'posts');
const [currentPosts, setCurrentPosts] = useState(null)
let allposts = []
useEffect(() => {
const q = query(colRef, orderBy('created_at'))
let posts = []
onSnapshot(q, (snapshot) => {
snapshot.docs.forEach((doc) => {
posts.push({ ...doc.data(), id: doc.id})
})
});
posts.forEach((post) => {
console.log(post)
allposts.push(
` <div className='pop-out h-[250px] w-[300px] md:h-[250px] md:w-[400px] lg:h-[250px] lg:w-[400px] border-2 cursor-pointer rounded-md m-auto md:m-auto lg:m-0'>
<h2 className='text-[30px] ml-5 mt-10 text-[gray]'>${post.title} by ${post.author}</h2>
<ArrowRightIcon className='relative w-9 left-[250px] top-[120px] md:left-[350px] md:top-[120px] lg:left-[350px] lg:top-[120px] text-orange-500'/>
</div>`
)
})
}, [])
console.log(allposts)
return (
<>
<div className="text-center text-[30px] text-white border-b-2 border-red-500 mt-10 mb-10">
Portfolio
</div>
<div>
{allposts}
</div>
</>
);
const db = getFirestore();
const colRef = collection(db, 'posts');
const [currentPosts, setCurrentPosts] = useState(null)
let allposts = []
useEffect(() => {
const q = query(colRef, orderBy('created_at'))
let posts = []
onSnapshot(q, (snapshot) => {
snapshot.docs.forEach((doc) => {
posts.push({ ...doc.data(), id: doc.id})
})
});
}, [])
if(posts.length>0){
return (
<>
<div className="text-center text-[30px] text-white border-b-2 border-red-500 mt-10 mb-10">
Portfolio
</div>
<div>
{posts.map(post=>(
<div className='pop-out h-[250px] w-[300px] md:h-[250px] md:w-[400px] lg:h-[250px] lg:w-[400px] border-2 cursor-pointer rounded-md m-auto md:m-auto lg:m-0'>
<h2 className='text-[30px] ml-5 mt-10 text-[gray]'>{post.title} by {post.author}</h2>
<ArrowRightIcon className='relative w-9 left-[250px] top-[120px] md:left-[350px] md:top-[120px] lg:left-[350px] lg:top-[120px] text-orange-500'/>
</div>
))}
</div>
</>
);}
else{
return <div>Loading.....</div>
}