This is my code to get the data from the firestore.
class PendingOrdersTable extends Component {
constructor() {
super();
this.state = { orders: [] };
}
columns = [
"Order ID",
"Items",
];
options = {
filter: true,
};
componentDidMount() {
try {
firestore
.collection("orders")
.where("orderStatus", "==", "Pending")
.get()
.then((snapshot) => {
const orders = [];
snapshot.docs.map((doc) => {
const orderID = doc.id;
const data = doc.data();
data.items.forEach((item) => {
orders.push({
"Order ID": doc.id,
Items: [item.productName, "(", item.qty, ")"],
});
});
});
this.setState({ orders: orders });
console.log(JSON.stringify(this.state.orders));
});
} catch (err) {
console.log(error);
}
}
render() {
return (
<div>
<MUIDataTable
title={"Orders"}
columns={this.columns}
data={this.state.orders}
options={this.options}
/>
</div>
);
}
}
]
The problem with this is that it renders separate rows for the same document ID. It's supposed to display the [q2P7DafXDvma6eMztEir],Tuna Pizza(1) and Vegetable Pizza(2) in one column.
this is the JSON object:
[
{
"Order ID": "q2P7DafXDvma6eMztEir",
Name: "Ruhn",
"Total Amount": 390,
Items: ["Tuna Pizza", "(", 1, ")"],
},
{
"Order ID": "q2P7DafXDvma6eMztEir",
Name: "Ruhn",
"Total Amount": 390,
Items: ["Vegetable Pizza", "(", 2, ")"],
},
];
This is the data in firestore and the "Items" here is in array:
Replace the snapshot.docs.map
method with the below code snippet, it will append the items for same doc.id
and will provide the desired output.
const orders = [];
snapshot.docs.map((doc) => {
const items = []
doc.data().items.forEach((item) => {
items.push(`${item.productName}(${item.qty})`);
});
orders.push({
"Order ID": doc.id,
Items: items
})
});