0

I'm fetching data from firestore ( an array of items ) which is asynchronous, and when I console log it everything is fine ( it displays array that I'm requesting ), but when I try to render it in React Component using Array.map nothing displays.

import React, {useEffect} from 'react';

const Likes = props =>{
     const likedPosts = []
     useEffect(() => {
        db.collection('postLikes')
            .where('postID', '==', props.uid)
            .get()
            .then(function(querySnapshot) {
                querySnapshot.forEach(function(doc) {
                    likedPosts.push(doc.data())
                })
            })
    }, [])

    return(
      <div>
        {likedPosts.map(post =>{
         return(
          <h1>{post.whoLiked}</h1>
         )
      })}
      </div>
    )


}

And after that it displays nothing for some reason. I tried literally everything. I'm stuck on this for 3 hours

1
  • Effects are for "side effects". like toggling a CSS class on the HTML that you generate irrespective of anything else. This is almost certainly not that, but much more like state data, for which you want useState. Commented Feb 20, 2020 at 23:13

1 Answer 1

1

It's a good idea to set the data you get back from Firebase to local state, then render it. So I'd make a tweak as follows:

Edit: A bit more explanation, what is happening is that the effect runs asynchronously with the first render. So while you're getting data back from FB, you've already rendered the initial array value (which is empty). And when you get data BACK from FB, you're not telling React to update your component (using setState), so the old data is still being shown. Below, I've added the appropriate setState call to add your new array to the local state and initiate a re-render.

const Likes = props =>{
     const [posts, setPosts] = useState([]);

     useEffect(() => {
        const likedPosts = [];
        db.collection('postLikes')
            .where('postID', '==', props.uid)
            .get()
            .then(function(querySnapshot) {
                querySnapshot.forEach(function(doc) {
                    likedPosts.push(doc.data())
                })
                setPosts(likedPosts);
            })
    }, [props.uid]);

    return posts.length > 0 ? (
      <div>
        {posts && posts.map(post =>{
         return(
          <h1>{post.whoLiked}</h1>
         )
      })}
      </div>
    ) : null;

}

Make sure to update your dependency array as I've done above.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.