Home > Enterprise >  react native add and update item in array
react native add and update item in array

Time:08-28

//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.

Note: 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 know my question is very simple but 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