Set values first and then render the component

Viewed 30

I am new to learning React. The issue here is, my AAPost component gets rendered before I am setting the value of posts constant.
I tried to use async & await earlier but it wasn't helping at all. There must be something I am doing wrong, could someone point me in the right direction? Thank you :)

  import React, { useEffect, useState } from 'react'
    import './AAFeed.css'
    import AAPost from './AAPost'
    import AATweetBox from './AATweetBox'
    import { db } from '../fbr'
    
    function AAFeed() {
    
      const [posts, setPosts] = useState([]);
    
      useEffect(()=>{
         db.collection('posts').onSnapshot((snapshot) => {
          setPosts(snapshot.docs.map(doc => doc.data()));
        });
        
      },[])
      
      return (
        <>
          <div className='feed'>
            {/* Header */}
            <div className='feed__feedtitle'>
              <h2>Home Page</h2>
            </div>
    
            {/* Tweet Box */}
            <AATweetBox />
    
            {/* Tweets */}
            {posts.forEach((post) => {
              console.log('pp',post);
              <AAPost
              displayName={post.displayName}
              username={post.username} 
              verified={post.verified} 
              timestamp={post.timestamp} 
              text={post.text} 
              image={post.image} 
              avatar={post.avatar}
              /> 
            })
            }
          </div>
        </>
      )
    }
    
    export default AAFeed
2 Answers

I think mummo is because you are using forEach

forEach does not return a value

{ posts.map((post) => {
    console.log('pp',post);
    return(<AAPost
        displayName={post.displayName}
        username={post.username} 
        verified={post.verified} 
        timestamp={post.timestamp} 
        text={post.text} 
        image={post.image} 
        avatar={post.avatar}
    />) })}

Visit this site for information.

add this before post.foreach and test it

if(post !== []){ post.foreach... }}

Related