Error fetching unit_price_measurement

ChrisAOO
Tourist
3 0 1

Hi all,

 

I built an cart view that uses product data from the Shopify AJAX API. Everything works fine so far, BUT:

implementing the

unit_price_measurement.reference_value

and

 

 

unit_price_measurement.reference_unit

 

throws an error. The data can be retrieved and displayed, but with the following error message:

 

Uncaught (in promise) TypeError: Cannot read property 'reference_value' of undefined

Bildschirmfoto 2020-05-15 um 11.36.26.png

This is my HTML (in JS) for displaying it

 

 

<div class="go-cart-item__unit-price">
            ${formatMoney(item.unit_price, this.moneyFormat)} <span>${
              item.unit_price_measurement.reference_value
            }</span> <span>${item.unit_price_measurement.reference_unit}</span></<div>

This is my fetch fucntion:

  fetchCart(callback) {
    window
      .fetch("/cart.js", {
        credentials: "same-origin",
        method: "GET",
      })
      .then((response) => response.json())
      .then((cart) => this.fetchHandler(cart, callback));
    try {
      throw new Error("Whoops! Fetching the cart failed somehow");
    } catch (e) {}
  }

Anybody who could help me here? Thanks a lot and cheers

 

0 Likes
SBD_
Shopify Staff
Shopify Staff
1043 141 183

Hey @ChrisAOO 

 

The unit_price_measurement property will only be available to items with a price.

 

It looks like your store has some €0,00 items. You could either add a price, or additional code to check for the property.

 

0 Likes
ChrisAOO
Tourist
3 0 1

Hey @SBD_ ,

 

thank you for the reply. Would it be correct to to something like this to check if the product has a unit price? I still get the same error here

 

      if (
       item.unit_price_measurement.reference_value !== "undefined" &&
        item.unit_price_measurement.reference_unit !== "undefined"
      ) {
        this.cartDrawerContent.innerHTML += cartSingleProductwithUnit;
      } else {
        this.cartDrawerContent.innerHTML += cartSingleProduct;
      }
0 Likes
ChrisAOO
Tourist
3 0 1

Ok, i solved it this way

 

      let unitPriceMeasurement = item.unit_price_measurement;
      if (unitPriceMeasurement !== undefined) {
        var unitPrice = formatMoney(item.unit_price, this.moneyFormat);
        var unitPriceValue = item.unit_price_measurement.reference_value;
        var unitPriceUnit = item.unit_price_measurement.reference_unit;
      }