shopify /cart/change.js

I need to re-match some item attributes in the shopping cart according to the quantity of added purchases, so I need to change each item in the shopping cart. Is there a delay in this request from Shopify? Because the request is successful from time to time, but it is not modified during checkout, I need to manually refresh the page several times before the change is successful.

Can anyone help me? Thank you very much

Hi @Simon_come :waving_hand: It’s a network request there is ALWAYS a delay; and it’s asynchronous ontop of that.
If manipulating the cart you need to wait/poll the cart until you know it’s ready.

If your customizing a theme this isn’t even accounting for what other things the theme may be doing or expect to properly update what it shows.

When in doubt make a minimal, reproducible example i.e. https://stackoverflow.com/help/minimal-reproducible-example , ex: https://mayert-douglas4935.myshopify.com/pages/api

fetch('/cart.js')
    .then(response => response.json())
    .then(async (cart) => {
        let diff_days = {{ diff_days_for_js }}
        let updatePromises = []; 
        let options = { year: 'numeric', month: 'short', day: 'numeric' };
        cart.items.reverse().forEach((item, index, array) => {
        let currentDate = new Date()
        let targetDate = new Date()
          let item_option = ''
          let item_estimated = ''
          let item_current_estimated = item.properties['Estimated']
          let item_current_method = item.properties['Delivery Method'].toLowerCase().replace(/\s+/g, "");
          for (const variant_item of variant_list) {
              if (variant_item.id == item.id) {
                if (variant_item.quantity - item.quantity >= 0) {
                  if (item_current_estimated == 'Plan A') {
                    item_estimated = item_current_estimated
                    currentDate.setDate(currentDate.getDate() + diff_days);
                    const formattedDate = currentDate.toLocaleDateString('en-GB', options).replace(/ /g, ' ');
                    item_option = `${item.quantity} estimated for ${item_current_method} by ${formattedDate}.`
                  }
                }
                variant_item.quantity = variant_item.quantity - item.quantity > 0 ? variant_item.quantity - item.quantity : 0 
              }
          }
          let obj = {
            "id":item.key,
            "quantity":item.quantity,
            "properties":{
              "Delivery Method":item.properties['Delivery Method'],
              "Delivery Option":item_option,
              "Estimated":item_estimated,
              "Project Name":item.properties['Project Name']
            }
          }
          updatePromises.push(fetch('/cart/change.js', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(obj)
          }).then(response => response.json())
            .then(data => {
              console.log("success");
            })
            .catch(error => {
              console.error(`Error updating item ${item.id}:`, error);
            })
          )
      });
      await Promise.all(updatePromises);
      setTimeout(function(){
        document.querySelector("safe-sticky").querySelector("button[name='checkout']").removeAttribute("disabled")
      },4000)
    })
    .catch(error => {
      console.error('Error fetching cart:', error);
    });

This is my code. When I enter the shopping cart page, I will request cart.js and then update all the products in the cart. Can you please help me see where I need to optimize?

Thank you very much!