'How can I get user displaynames who posted comments with Firestore v9 in React
I'am using Firestore v9 and i try to get users comment with onsnapshot After i reach the datas i try to get user displayname who commented. I can pull the data without any problem, but it doesn't render.
Here is my useEffect Function
useEffect(async () => {
setLoading(true);
const datas = [];
const unsubscribe = onSnapshot(
query(
collection(
db,
'workspace',
currentWorkspace,
'pages',
activeDecision.id,
'ideas'
),
orderBy('createdAt', 'desc')
),
(querySnapshot) => {
const snapData = querySnapshot.docs.map(async (snap) => {
const userRef = doc(db, 'user', snap.data().user);
const user = await getDoc(userRef);
datas.push({
id: snap.id,
idea: snap.data().idea,
user: snap.data().user,
displayName: user.data().displayName, // <---
});
});
setIdeas(datas); //<-- no problem everything seems good.
setLoading(false); //<-- loading false for rerendering
}
);
return () => unsubscribe();
}, []);
Here is my return func.
return (
!loading &&
(
<Wrap spacing="30px">
{ideas?.map((item, index) => (
<WrapItem key={index}>
<Stack p="4" boxShadow="base" borderRadius="sm" maxW={'265px'}>
<Stack direction="row" alignItems="center">
<Avatar
size="sm"
name={item.displayName.toLowerCase()}
cursor="pointer"
/>
<Text fontWeight="semibold">{item.displayName}</Text>
</Stack>
<Stack
direction={{ base: 'column', md: 'row' }}
justifyContent="space-between"
>
<Text>{item.idea}</Text>
</Stack>
</Stack>
</WrapItem>
))}
</Wrap>
)
);
The interesting thing is that after this snapshot, when I removed userRef and user, react rendering perfectly. So the problem may be occurring because I'm pulling data from another collection after onSnaphot.
const userRef = doc(db, 'user', snap.data().user);
const user = await getDoc(userRef);
How can I use onSnaphot then get datas from different collection ? Thank you
Solution 1:[1]
firebase.js
import { initializeApp } from 'firebase/app';
import { getFirestore } from "firebase/firestore";
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
databaseUrl: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
user.js
import { db } from "./firebase";
import { collection, addDoc, getDocs } from "firebase/firestore";
export const getuser = async () => {
try {
const querySnapshot = await getDocs(collection(db, "user"))
return querySnapshot
}
catch (e) {
console.error("Error adding document: ", e);
}
}
import React, { useEffect, useState } from 'react'
import { getuser } from './user.js'
export default function Home() {
const [user, setUser] = useState([])
useEffect(() => {
let data = await getuser()
let users = []
data.forEach(doc => {
users.push(doc.data())
})
setUser(users)
}, []);
return (
<div>
{user.map((item, index) => (
<div>
<p>{item.displayName}</p>
<p>{item.idea}</p>
</div>
))}
</div>)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Meet Bhavsar |
