Search code examples
javascriptdjangodjango-rest-framework

Updating quantity in javascript


Items are been added to the cart successfully and when clicking a button with data-action add it successfully adds +1 to the quantity, how ever when i click a button with a data action of remove it still adds +1 to quantity, it seems that the PATCH request is never been initialized but I cannot see why.

So currently:

data action add = +1 to item quantity data action add = +1 to item quantity

I want:

data action add = +1 to item quantity data action add = -1 to item quantity

const updateBtns = document.querySelectorAll(".update-cart");
const user = "{{request.user}}";

for (let i = 0; i < updateBtns.length; i++) {
  updateBtns[i].addEventListener("click", function () {
    event.preventDefault(); // prevent page from refreshing
    const productId = this.dataset.product;
    const action = this.dataset.action;
    console.log("productId:", productId, "action:", action);
    console.log("USER:", user);
    createCart(productId, action);
  });
}

function createCart(productId, action, cartId) {
    var csrftoken = getCookie('csrftoken');
    console.log('User is logged in, sending data...');
    fetch('/get_cart_id/')
        .then(response => response.json())
        .then(data => {
            const cartId = data.cart_id;
            console.log('Cart ID:', cartId); // log cartId in console
            
            // get the cart items for the given cart
            fetch(`/api/carts/${cartId}/items/`)
                .then(response => response.json())
                .then(data => {
                    let itemExists = false;
                    let cartItemId = null;
                    let quantity = 1;
                    
                    // check if the product is already in the cart
                    for (let i = 0; i < data.length; i++) {
                        if (data[i].product_id === parseInt(productId)) {
                            itemExists = true;
                            cartItemId = data[i].id;
                            quantity = action === 'remove' ? data[i].quantity - 1 : data[i].quantity + 1;
                            break;
                        }
                    }
                    
                    // if the item exists, update the quantity
                    if (itemExists) {
                        fetch(`/api/carts/${cartId}/items/${cartItemId}/`, {
                            method: 'PATCH',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': csrftoken
                            },
                            body: JSON.stringify({
                                quantity: quantity
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            console.log('Item quantity updated:', data);
                        });
                    } else { // add the item to the cart
                        fetch(`/api/carts/${cartId}/items/`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': csrftoken
                            },
                            body: JSON.stringify({
                                product_id: productId,
                                quantity: 1
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            console.log('Item added to cart:', data);
                        });
                    }
                });
        });
}

fetch data when hitting a data-action remove button:

get_cart_id/:

enter image description here

items/:

enter image description here

items/ for a second time:

enter image description here


Solution

  • So you're hitting the /items endpoint and getting an array of objects back, which don't have a product_id property. It looks like you need to update your if statement in your for loop to: if (data[i].product.id === parseInt(productId)) so that it can set itemExists properly.