Vishali
Vishali

Reputation: 1397

Add and update item in array in React Native

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.

Upvotes: 0

Views: 404

Answers (1)

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11930

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
    }
}

Upvotes: 1

Related Questions