const [postList, setPostList] = useState([])
const q = query(collection(db, "examples"), where("title", "==", title))
try {
const posts = await getDocs(q)
posts.forEach((doc) => {
console.log(doc.data())
})
} catch (e) {
console.log(e.message)
}
I tried to check the docs list i got from query with console. log , the list is fine and it's what I expected. The problem got me is, i am not sure if i did it right, when i tried to set the document lists i query to the state object. Below is what i did
const q = query(collection(db, "examples"), where("title", "==", title))
try {
const posts = await getDocs(q)
posts.forEach((doc) => {
setPostList(...postList, doc.data())
})
} catch (e) {
console.log(e.message)
}
I subsequently tried to map data I want into components. It said
"Uncaught TypeError: postList.map is not a function".
Please kindly advise how I could put doc.data()
into iterable. Thanks.
const getData = async () => {
const q = query(collection(db, "data"), where("title", "==", title))
try {
const posts = await getDocs(q)
const data = posts.docs.map((doc) => ({ id: doc.id, ...doc.data() }))
setPostList(data)
}
catch (e) {
console.log(e.message)
}
}
......... .....
postList.map((doc) => {
<Block question={doc.data().item} answer={doc.data().details} />
CodePudding user response:
postList
must be an array in this case so you use map()
. But setPostList(...postList, doc.data())
will be an object. Try refactoring the code as shown below:
const posts = await getDocs(q)
const data = posts.docs.map((d) => ({ id: d.id, ...d.data() }))
setPostList(data)