I have an array, I push doc data from firebase into that array and I want to display a table row for each doc. The problem is that the map method won’t do anything.
const [allScores,setAllScores] = useState([]) async function getAllScores(){ const q = query(collection(db, "allScores"), orderBy("score", "desc")); const querySnapshot = await getDocs(q); querySnapshot.forEach((doc) => { // doc.data() is never undefined for query doc snapshots /* allScores.push(doc.data()) */ allScores.push(doc.data()) }) } useEffect(() => { getAllScores() }, []) <table className="text-white text-center"> <tbody> <tr> <td className="px-[205px] text-xl">Place</td> <td className="px-[205px] text-xl">User</td> <td className="px-[205px] text-xl">Score</td> <td className="px-[205px] text-xl">Scored at</td> </tr> {allScores.map(score => ( place = place + 1, <tr> <td className="px-[205px] text-xl w-auto">{place}</td> <td className="px-[205px] text-xl w-auto">{score.playerName}</td> <td className="px-[205px] text-xl w-auto">{score.score}</td> {/* <td className="px-[210px] text-xl">{score.scoredAt}</td> */} </tr> ))} </tbody> </table>
Advertisement
Answer
First of all, you need to update the state by setAllScores
async function getAllScores(){ const q = query(collection(db, "allScores"), orderBy("score", "desc")); const querySnapshot = await getDocs(q); querySnapshot.forEach((doc) => { setAllScores(prev => { return [...prev, doc.data()] } }) }