I have a ReactJS component that renders a list of orders. I get orders from a REST API. The format of the data is the following:
{
"count": 2,
"orders": [
{
"order_number": 55981,
"customer_number": 24742
},
{
"order_number": 55980,
"customer_number": 24055
}
]
}
Each order can have a list of items. When I click on an order, I get the list of items in the following format:
{
"count": 2,
"items": [
{
"name": "Green pillow",
"status": "pending"
},
{
"name": "Red pillow",
"status": "delivered"
}
]
}
The orders list is refreshed automatically and can change any time, so I store the orders list in this.state which gets updated via ajax.
this.state looks like this:
{
"orders": [
{
"order_number": 55981,
"customer_number": 24742
},
{
"order_number": 55980,
"customer_number": 24055
}
]
}
My problem is that I would like that, when I click on an order, the state gets updated so that the clicked order contains the items associated to that order. The order list would look like this after clicking on an item:
{
"count": 2,
"orders": [
{
"order_number": 55981,
"customer_number": 24742,
"items": [
{
"name": "Green pillow",
"status": "pending"
}
]
},
{
"order_number": 55980,
"customer_number": 24055
}
]
}
How can I add items to a specific order using this.setState()? The problem is that setState seem to update data using keys, but my orders are in an array. I can probably copy the whole array and put the items key inside, but that seems overkill. Am I taking the wrong approach?