Necesito poner los datos obtenidos en una tabla (es un CRUD muy simple)
He probado poner la función map() fuera de la función Management() pero no funciona.
Aquí está mi código:
let allUsers = []; function Management() { useEffect(() => { const fetchData = async () => { try { const querySnapshot = await getDocs(collection(db, "users")); let allDocs = []; querySnapshot.forEach((doc) => { allDocs.push({ ...doc.data(), id: doc.id }); }); for (const item of allDocs) { const querySnap = await getDocs( collection(db, `users/${item.id}/general`) ); allUsers.push( querySnap._snapshot.docChanges[0].doc.data.value.mapValue.fields .data.mapValue.fields ); } } catch (err) { console.log(err); } }; fetchData(); }, []); return ( <Table> <thead> <tr> <th>#</th> <th>Nom</th> <th>Prénom</th> <th>Email</th> </tr> </thead> <tbody> {allUsers.map((user) => { return ( <tr> <th scope="row">1</th> <td>{user.email.stringValue}</td> <td>a</td> <td>@mdo</td> </tr> ); })} </tbody> </Table> ); } export default Management;El problema ocurre en la función allUsers.map().
Parece que devuelve una matriz vacía.
No está cambiando el estado del componente Dado que está utilizando un componente funcional, utilice useState.
function Management() { const [allUsers , setAllUsers] = React.useState<any>([]); useEffect(() => { const fetchData = async () => { let allUsersData=[]; try { const querySnapshot = await getDocs(collection(db, "users")); let allDocs = []; querySnapshot.forEach((doc) => { allDocs.push({ ...doc.data(), id: doc.id }); }); for (const item of allDocs) { const querySnap = await getDocs( collection(db, `users/${item.id}/general`) ); allUsersData.push( querySnap._snapshot.docChanges[0].doc.data.value.mapValue.fields .data.mapValue.fields ); setAllUsers(allUsers); } } catch (err) { console.log(err); } }; fetchData(); }, []); return ( <Table> <thead> <tr> <th>#</th> <th>Nom</th> <th>Prénom</th> <th>Email</th> </tr> </thead> <tbody> {allUsers.map((user) => { return ( <tr> <th scope="row">1</th> <td>{user.email.stringValue}</td> <td>a</td> <td>@mdo</td> </tr> ); })} </tbody> </Table> ); } export default Management;