So, I have a useState
that contains data like this:
const [orderData, setOrderData] = useState({
demoData1: '',
demoData2: '',
demoData3: '',
demoArrayData: [{itemName: '', itemNumber: ''}]
});
I have an onClick
function that I would like to use to update the demoArrayData
. However, I want to check if the item I want to add into the demoArrayData
already exist, if it already there in the array, update it with the latest information and return both the updated item and other items there.
If the item is not on the array, add it to the array and return both the newly added item and other items there before. I have this onClick
function:
const handlePackageSizeSelection = (selectedItem: number, itemIndex: number, selectedItemName: string, selectedItemPrice: string )=>{
const orderedListInfo: orderedItemListAttributes = {
orderedItemName: selectedItemName,
orderedQuantity: selectedItem?.toString(),
orderItemPrice: selectedItemPrice,
orderItemSelectedIndex: itemIndex?.toString()
}
setOrderData({...orderData, demoArrayData:[...orderData?.orderedItemList as [], orderedListInfo]})
setOrderPackageArrayData(updatedArray);
};
While this works, it will add same item more than once. Is there a way to make it detect an item that is already in the array, update it and return everything from the state or add the item to the array if not on the array list?
4
Answers
You can use
Array#some
to check for a matching name before deciding how to update.you can try this syntax
If I am understanding your question correctly then we can divide the task into steps, that will help you write a readable and clean code also:
you should use function to update state based on previous state and you should check if updating item exists in previous state or not.
try to update orderDataState this way: