Estoy tratando de mostrar todas las 'publicaciones' de mi base de datos en diferentes divs. El código obtiene las publicaciones y las inserta en la matriz de publicaciones. Aquí viene el problema. El método posts.forEach debería ejecutarse pero no lo hace. No empujará los div en la matriz allposts. Incluso el console.log no se ejecutaría. Al final, allposts devuelve una matriz vacía. ¿Alguien sabe cuál podría ser el problema? No puedo resolverlo.
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> }