I am having trouble getting the desired result I am looking for on an update function.
The goal for this code is to post to an API so the schema for the array of objects is something I am trying to refrain from changing.
const initialItem = [{
Item": {
"ItemDetail": {
"ItemID": "string",
"ItemDescription": "string"
}
},
"ItemCode": {
"Code": "string"
}
}];
const [items, setItems] = useState(initialItem);
const updateItem = (index, field, value) => {
setItem(produce(items, draft => {
draft[index][field] = value;
}));
};
const handleItemChange = (selectedItem) => {
updateItem(index, 'ItemDetail',
{ Item:
{ ItemID: selectedItem.ItemID,
ItemDescription: selectedItem.ItemDescription }
});
updateItem(index, 'ItemCode', { Code: selectedItem.Code });
};
I expect this code to yield the following result:
Item: {
ItemDetail: {
ItemID: '0000',
ItemDescription: 'Description of item 0000'
}
},
ItemCode: {
Code: '42069'
}
However, my handleItemChange()
function is ignoring the first call to updateItem()
and my result yields:
Item: {
ItemDetail: {
ItemID: 'string',
ItemDescription: 'string'
}
},
ItemCode: {
Code: '42069'
}
I can also update my handleItemChange()
function to:
const handleItemChange = (selectedItem) => {
updateItem(index, 'ItemCode', { Code: selectedItem.Code });
updateItem(index, 'ItemDetail',
{ Item:
{ ItemID: selectedItem.ItemID,
ItemDescription: selectedItem.ItemDescription }
});
};
And that yields this result:
Item: {
ItemDetail: {
ItemID: '0000',
ItemDescription: 'Description of item 0000'
}
},
ItemCode: {
Code: 'string'
}