0

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.

2
  • Vishali, please note that Stack Overflow is not a chatroom. Readers would like you to pay attention to spelling and case in order to maintain maximum readability. In particular the personal pronoun "I" uses a capital letter - there are no exceptions to this rule. Commented Aug 28, 2022 at 10:37
  • Sentences finish with a full stop and are separated with a space, except where they indicate that something is to follow, in which case they end with a colon. Paragraph text should not start with a double slash - it is not a comment. Commented Aug 28, 2022 at 10:38

1 Answer 1

1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.