1
I am receiving data from Firebase with Reactjs and my problem is that I want to organize this data in the table as follows:
But I can’t do it, that’s the result I got:
I know it is a relatively simple problem and would be grateful if someone could help. Below is my code.
function Exemplo() {
const [users, setUsers] = React.useState([])
React.useEffect(() => {
// const db = firebase.firestore()
// db.collection('equipes').onSnapshot(data => {
// setUsers(data.docs.map(doc => ({ ...doc.data() })))
// })
// Esses são os dados mapeados do firebase:
setUsers([
{
"name": "Furia",
"players": [
{ "name": "Eduardo", "attack": 18, "defense": 2 },
{ "name": "Tiago", "attack": 15, "defense": 3 },
{ "name": "Julia", "attack": 10, "defense": 0 }
]
},
{
"name": "Incriveis",
"players": [
{ "name": "Eduardo", "attack": 11, "defense": 4 },
{ "name": "Tiago", "attack": 17, "defense": 0 },
{ "name": "13", "attack": 13, "defense": 6 }
]
}
]);
}, [])
if (users) {
return (
<div>
<table>
<thead>
<tr>
<th rowSpan="2">#</th>
<th rowSpan="2">Nome</th>
<th colSpan="2">Furia</th>
<th colSpan="2">Incriveis</th>
</tr>
<tr>
<td>Ataques</td>
<td>Defesas</td>
<td>Ataques</td>
<td>Defesas</td>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<React.Fragment key={index}>
{user.players.map((u, index) => (
<tr key={index}>
<td>{index + 1}</td>
<td>{u.name}</td>
<td>{u.attack}</td>
<td>{u.defense}</td>
</tr>
))}
</React.Fragment>
))}
</tbody>
</table>
</div>
)
}
}
ReactDOM.render(<Exemplo />, document.querySelector("#container"));
<div id="container"></div>
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
Instead of sharing a Firebase print, it’s easier to share what your array
users
possesses as value. What it seems to me is that the person is repeated inuser.players
, would need to make a.reduce
if that’s right.– Rafael Tavares
Thanks for the touch. But it’s really repeated. The idea is for the team to be associated with players like the first image of the table I showed. I structured in the firestore in that way as an example, because I had no better idea.
– Bruno Lucas
All right, buddy, I added
– Bruno Lucas
The answer solved your problem, Bruno?
– Rafael Tavares
Actually the data will be dynamic using a form to add. I put only 2 teams and 3 sample players. About the database the structure I put was to have an idea. But your answer is helping me to have some ideas. If I can solve the problem or have any questions back with the feedback. Thank you!
– Bruno Lucas