I'm trying to create a dynamic table so that every time I press the "add" button, a new row will be created.
In my example below, it creates only 1 row with all the data under its header, but with all the 3 values in this case instead of create a new row.
I'm fetching the document from Firestore and the collection includes only 1 document with an array inside, in this case with 3 values.
here is the screenshot of the table it creates:
Expecteed table example:
Code:
export default class NutritionTableOfTheUser extends Component {
constructor() {
super();
this.state = {
tableData: []
}
}
componentDidMount() {
const dbRef = collection(db, 'data');
onSnapshot(dbRef, (querySnapshot) => {
let foods = [];
querySnapshot.forEach(doc => {
foods.push(doc.data())
});
this.setState({ tableData: foods })
})
}
render() {
return (
<div className='container mt-3'>
{/* table */}
<table className='table table-hover'>
<thead>
<tr>
<th>#</th>
<th>Food</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
{this.state.tableData.map((row, index) => {
return (
<tr>
<td>{index 1}</td>
<td>{row.value}</td>
<td>{row.quantity}</td>
</tr>
)
})}
</tbody>
</table>
</div>
)
}
}
CodePudding user response:
You should check the data you are getting from firebase collection, because you might have only one document in collection which results in rendering only one row in table.
CodePudding user response:
It looks like you only have a single document, and your .value
and .quantity
properties of the row are arrays (rather than numbers) - so doing <td>{row.value}</td>
mashes all values of the array together.
Turn the .data()
into the desired data format first, then set the state with it.
querySnapshot.forEach(doc => {
const [obj] = doc.data();
const tableData = obj.value.map((value, i) => ({
value,
quantity: obj.quantity[i]
}));
this.setState({ tableData })
});