Have your say in Community Polls: What was/is your greatest motivation to start your own business?

Cart API change url not updating properly

Solved

Cart API change url not updating properly

jonah_toral
Visitor
2 1 0

I am having issues with the Cart API being heavily inconsistent. I am hijacking the change quantity fetch request to add a virtual product to the cart when the change quantity succeeds and then updating the state to the virtual product state so that the HTML re-render shows the new product. The issue is that while it might render the new product or render the change in quantity of the new product, it isn't until you reload the page like 3 times that it will actually reflect that change in the checkout. Another example is when you delete the product entire from the cart the virtual product is meant to disappear as well, but instead if you reload the virtual product will re-appear by itself and if you reload again it will then disappear for real and not show up in the cart. The code that hijacks the change fetch request from the update quantity is exactly the same code we used from August 2023 to February 2024 and it worked perfectly then, but now it seems to not be working. All the functionality is working off of Dawn with some parts customised.

This is the function that calls the cart API to add the product to the cart.

 

 

 

// Function to add gift wrap to the cart using the previous and new quantity and init to determine whether it is first DOM load
  updateGiftWrap(previousQuantity, newQuantity) {
    // Setting the variant ID for the gift wrap
    let variantID = '53511628620155';

    console.log('this ran');

    // Calculating the total gift wrap needed
    // By adding the new quantity minus the previous quantity to the amount needed
    amountOfGiftWrapNeeded = parseInt(amountOfGiftWrapNeeded) + parseInt(newQuantity) - parseInt(previousQuantity);

    // Creating an object that holds the data for the gift wrap as well as the sections that need reloading
    const body = JSON.stringify({
      id: variantID,
      quantity: amountOfGiftWrapNeeded,
      sections: this.getSectionsToRender().map((section) => section.section),
      sections_url: window.location.pathname,
    });

    // Creating a state variable that fetches the change to the gift wrap quantity as well as the
    // section html change
    const state = fetch(`${routes.cart_change_url}`, {
      ...fetchConfig(),
      ...{ body },
    })
      .then((response) => {
        if (response.status == 200) {
          // Changing the gift wrap amount to the current gift wrap amount
          giftWrapAmount = amountOfGiftWrapNeeded;
        }
        return response.text();
      })
      .then((state) => {
        // returning the html code
        return state;
      })
      .catch((e) => {
        console.error(e);
      });

    // returning the html code
    return state;
  }

 

 

 

This is the part of the Dawn code that is edited to hijack the update quantity function

 

 

// Adding a boolean gift wrap value as well as the current quantity value
  // Changing the updateQuantity to updateLineItem and adding a newGiftMessage that defaults to undefined
  // Adding data when updating the properties of a line item
  updateLineItem(line, quantity, name, hasGiftWrap, currentQuantity, newGiftMessage = undefined, data) {
    this.enableLoading(line);

    // Making the body
    let body = {
      line,
      quantity,
      sections: this.getSectionsToRender().map((section) => section.section),
      sections_url: window.location.pathname,
    };

    // If statement that remakes the body object to hold the new gift message
    if ((newGiftMessage || newGiftMessage == '') && data) {
      // Adding the properties from data
      body = {
        line,
        quantity,
        properties: { ...data[line - 1].properties },
        sections: this.getSectionsToRender().map((section) => section.section),
        sections_url: window.location.pathname,
      };

      // Updating the Gift message
      body.properties['Gift Message'] = newGiftMessage;
    }

    fetch(`${routes.cart_change_url}`, {
      ...fetchConfig(),
      body: JSON.stringify(body),
    })
      .then((response) => {
        let state = response.text();
        // If the change is successfull and the line item has gift wrapping it gets new html code from the
        // gift wrap function to parse
        // Adding another condition to not run when the quanity is not changing
        if (response.status === 200 && hasGiftWrap && quantity !== currentQuantity) {
          state = this.updateGiftWrap(currentQuantity, quantity);
        }

        return state;
      })

 

 

 

jonah_toral_0-1730906423718.png

Screenshot 2024-11-06 at 15.22.44.png

When you remove the product and then reload the Paid Gift Box comes back by itself. Once you reload again it's gone for real.

Screenshot 2024-11-06 at 15.23.25.png

 

 

 

Accepted Solution (1)

jonah_toral
Visitor
2 1 0

This is an accepted solution.

I fixed the issue. After some research I concluded that it might be a race condition. Because of the async nature of Javascript, sometimes one fetch request would finish first, sometimes the other would finish first. Instead, I decided to change the cart file so that it would call the update API endpoint when it needed to change two cart item quantities at the same time, and use the change API endpoint when it needed to change the quantity of any other product that wasn't bundled with the virtual product.

View solution in original post

Reply 1 (1)

jonah_toral
Visitor
2 1 0

This is an accepted solution.

I fixed the issue. After some research I concluded that it might be a race condition. Because of the async nature of Javascript, sometimes one fetch request would finish first, sometimes the other would finish first. Instead, I decided to change the cart file so that it would call the update API endpoint when it needed to change two cart item quantities at the same time, and use the change API endpoint when it needed to change the quantity of any other product that wasn't bundled with the virtual product.