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 Answer 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.
useState.