Home > Mobile >  Add and update item in array in React Native
Add and update item in array in React Native

Time:08-29

Here is my code:

if(basketdata.length > 0){
      for(var i = 0 ;i<basketdata.length; i  ){
        //update quantity in list if same item is selected more than one time
       if(temp.id == basketdata[i].id){
        console.log('updateitem');
        basketdata[i].quantity = addQuantity;
        break;
       }else{
        basketdata.push(temp);
       break;
      }
      }
    }else{
      console.log('newitem');
      basketdata.push(temp);
    }

I have flatlist with two buttons plus and minus in my React Native application. If user clicks the item in list I want to add that item in array and again if user tried to click the same item I want to update the quantity parameter in the item instead of adding new item.

Notes:

  1. I want to update the item if user selects same item
  2. Add new item in array if user selects different item in flatlist

I tried as much as possible to fix but I am not able to make actual output.

CodePudding user response:

You should not use for loop here, use .findIndex()

function handle (temp) {
    const index = basketdata.findIndex(v => v.id === temp.id)

    if (index > -1) {
        basketdata[index].quantity = addQuantity
    } else {
        basketdata.push(temp)
    }
}

Ideally addQuantity shouldn't be used, and also, if your baskeddata is state, then here's better approach

// id is temp id
// amount is either 1 or -1
function handle (id, amount) {
    const index = basket.findIndex(v => v.id === temp.id)

    if (index > -1) {
        if ((basket[index].quantity   amount) >= 0) {
            basket[index].quantity = basket[index].quantity   amount
            setState(basket)
        }
    } else {
        setState(basket.concat({
           id,
           quantity: 1
        })) // here we store only { id, quantity } fields in basket
    }
}
  • Related