I have a React app with Firebase backend. I have a users collection in the database which stores the photoURL of the user.
When a user comments on a post, instead of saving that photoURL each time into the comments collection I just want to render the photoURL from the users collection.
That way if the user updates their photoURL it is updated on all the comments plus there's no duplication of data.
On each comment I have saved the uid in the comment collection. I just can't quite figure out how to map through all the comments and take the uid and use that to get the photoURL from the users collection. Below is what I have so far.
I'm new to React so apologies if this is a simple fix.
const [comments, setComments] = useState([])
// This is used to get all the comments
useEffect(() => {
let unsubscribe
if (postId) {
unsubscribe = db.collection('posts').doc(postId).collection('comments').orderBy('timestamp', 'desc').onSnapshot((snapshot) => {
setComments(snapshot.docs.map((doc) => doc.data()))
})
}
return () => {
unsubscribe()
}
}, [postId])
// This is for adding the comment to the comments collection
const postComment = (event) => {
event.preventDefault()
db.collection('posts').doc(postId).collection('comments').add({
text: comment,
username: user.displayName,
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
photoURL: user?.photoURL, // This does not save anything because it's taking form auth user and not user collection
uid: user?.uid
})
setComment('')
setCommentActive(true)
setCommentsArrow(!commentsArrow)
}
// This is a function to get the photoURL of any user based on the uid
async function getImageURL(uid) {
return (await db.collection("users").doc(uid).get()).data().photoURL
}
// Rendering the comments
return (
<div style={{ transition: "height 0.3s linear" }} className={commentActive ? null : "hidden"}>
<div className="post__comments">
{comments.map((comment) => (
<div className="post__comment">
<Avatar
className="post__avatar"
alt=""
src={getImageURL(comment.uid)} // Calls the getImageURL function and passes in the uid from the comment
/>
<p><strong>{comment.username}</strong> {comment.text}</p>
</div>
))}
</div>
</div>
)