Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

javascript - How to update cart quantity if item already exist in Cart - reactjs?

in this code, instead of showing "The product has been added to cart." alert message, I want to update cart quantity if item already exist in cart, please help me out.

const addToCart = (id) => {
    const check = cart.every((item) => {
      return item.id !== id;
    });
    if (check) {
      const cartData = products.filter((el) => {
        return el.id === id;
      });
      setCart([...cart, ...cartData]);
    } else {
      alert('The product has been added to cart.');
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I am making some assumptions here as to what your variables look like, but generally, here is what you need:

const products = [{id: 1, name: 'Prod 1'}, {id: 2, name: 'Prod 2'}, {id: 3, name: 'Prod 3'}, {id: 4, name: 'Prod 4'}]
const cart = [{id: 1, name: 'Prod 1', quantity: 1}, {id: 4, name: 'Prod 4', quantity: 1}];

const addToCart = (id) => {
    const check_index = cart.findIndex(item => item.id === id);
    if (check_index !== -1) {
      cart[check_index].quantity++;
      console.log("Quantity updated:", cart);
    } else {
      cart.push({...products.find(p => p.id === id), quantity: 1})
      console.log('The product has been added to cart:', cart);
    }
}

addToCart(4)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...