skip to Main Content

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


  1. You can use Array#some to check for a matching name before deciding how to update.

    const orderedListInfo = {
        itemName: selectedItemName,
        orderedQuantity: selectedItem?.toString(),
        orderItemPrice: selectedItemPrice,
        orderItemSelectedIndex: itemIndex?.toString()
    };
    setOrderData({
        ...orderData,
        demoArrayData: orderData.demoArrayData.some(o => o.itemName === orderedListInfo.itemName) ?
            orderData.demoArrayData.map(o => o.itemName === orderedListInfo.itemName ? orderedListInfo : o) :
            [...orderData.demoArrayData, orderedListInfo]
    });
    
    Login or Signup to reply.
  2. you can try this syntax

    const handlePackageSizeSelection = (selectedItem: number, itemIndex: number, selectedItemName: string, selectedItemPrice: string )=>{
      
    
        const orderedListInfo: orderedItemListAttributes = {
            orderedItemName: selectedItemName,
            orderedQuantity: selectedItem?.toString(),
            orderItemPrice: selectedItemPrice,
            orderItemSelectedIndex: itemIndex?.toString()
        }
         setOrderData(prevState => ({
          ...prevState,
          demoArrayData: [...prevState.list, orderedListInfo],
        }))
        setOrderPackageArrayData(updatedArray);       
       
    };
    
    Login or Signup to reply.
  3. 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:

    const handlePackageSizeSelection = (selectedItem: number, itemIndex: number, selectedItemName: string, selectedItemPrice: string ) => {
     const newOrderItemToBeAdded: orderedItemListAttributes = {
      orderedItemName: selectedItemName,
      orderedQuantity: selectedItem?.toString(),
      orderItemPrice: selectedItemPrice,
      orderItemSelectedIndex: itemIndex?.toString()
    }
    
    // Check if the item to be add is already there in the demoArrayData
    const existingDemoArrayData = [...orderData.demoArrayData];
    
    // You can create a separate util function for this
    const alreadyPresentItemIndex = existingDemoArrayData.findIndex(demoItem => demoItem.name === newOrderItemToBeAdded.name);
    
    if (alreadyPresentItemIndex >= 0) {
      // Remove the existing item and insert the new one
      existingDemoArrayData.splice(alreadyPresentItemIndex, 1, newOrderItemToBeAdded);
    } else {
      // If it is not there already
      existingDemoArrayData.push(newOrderItemToBeAdded);
    }
    
    setOrderData({...orderData, demoArrayData: [...existingDemoArrayData]});
    
    return existingDemoArrayData;
    };
    
    Login or Signup to reply.
  4. 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:

    setOrderData(prevState => {
        if (prevState.demoArrayData.find(item => item.itemName === selectedItemName)){
            const otherItems = prevState.demoArrayData.filter(item => item.itemName === selectedItemName);
            return({...prevState, demoArrayData:[...otherItems , orderedListInfo]}) 
    
        }else{
            return({...prevState, demoArrayData:[...prevState?.orderedItemList , orderedListInfo]}) 
        }                
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search