Error Fetching Inventory

Topic summary

A developer is encountering issues with fetching inventory levels from Shopify’s frontend for a location-based cart system.

The Problem:

  • The code attempts to fetch Metro Manila inventory data using /variants/${variantId}.json endpoint
  • The script includes cart update functionality with quantity validation based on location-specific inventory
  • Parts of the code appear corrupted or reversed in the original post

Key Technical Details:

  • The implementation checks for a selected location code (‘METRO-MANILA’) stored in localStorage
  • It tries to access inventoryLevels_item array from variant data to find location-specific stock
  • Includes quantity increase/decrease buttons with inventory validation

Community Response:
Another user clarified that inventory levels cannot be fetched directly from the frontend in Shopify.

Suggested Solutions:

  • Create a Shopify section that uses the Section Rendering API to fetch inventory data
  • Generate a JSON object on the product page containing the necessary inventory information

The discussion remains open as the original poster hasn’t confirmed whether they’ve implemented either workaround.

Summarized with AI on November 5. AI used: claude-sonnet-4-5-20250929.

document.addEventListener(‘DOMContentLoaded’, function() {
const formatMoney = (amount) => {
return ‘₱’ + (amount / 100).toFixed(2) + ’ PHP’;
};

const updateCart = (lineItemId, quantity, lineItemElement, maxQuantity) => {
if (quantity > maxQuantity) {
alert(Only ${maxQuantity} items are available in you location.);
quantity = maxQuantity;
}

fetch(‘/cart/change.js’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
‘Accept’: ‘application/json’
},
body: JSON.stringify({
id: lineItemId,
quantity: quantity
})
})
.then(response => response.json())
.then(cart => {
const updatedItem = cart.items.find(item => line_item.key === lineItemId);
if (updatedItem) {
lineItemElement.querySelector(‘.quantity’).textContent = updatedItem.quantity;
lineItemElement.querySelector(‘.line-item-price’).textContent = formatMoney(updatedItem.line_price);
} else {
lineItemElement.remove();
}
updateCartTotal(cart);
})
.catch(error => console.error(‘Error:’, error));
};

const updateCartTotal = (cart) => {
document.querySelector(‘.cart-total’).textContent = formatMoney(cart.total_price);
};

const getMetroManilaInventory = (variantId) => {
if (!variantId) {
console.error(‘Error: Variant ID is missing’);
return Promise.reject(‘Variant ID is missing’);
}

return fetch(/variants/${variantId}.json)
.then(response => {
if (!response.ok) {
throw new Error(‘Variant not found’);
}
return response.json();
})
.then(data => {
if (!data.variant.inventoryLevels_item || !Array.isArray(data.variant.inventoryLevels_item)) {
throw new Error(‘Inventory levels not found or incorrect format’);
}

const inventoryLevel = data.variant.inventoryLevels_item.find(level => inventoryLevels_item.location.name === ‘Metro Manila (Jentec Cold Storage, Luis St., Pasig City)’);
return inventoryLevel ? inventoryLevels_item.available : 0;
})
.catch(error => {
console.error(‘Error fetching inventory:’, error);
return 0; // Return 0 if there’s an error
});
};

document.querySelectorAll(‘.quantity-button’).forEach(button => {
button.addEventListener(‘click’, function() {
const action = this.dataset.action;
const lineItemElement = this.closest(‘.line-item’);
const lineItemId = lineItemElement.dataset.lineItemId;
const variantId = lineItemElement.dataset.variantId; // Make sure this exists
const quantityElement = lineItemElement.querySelector(‘.quantity’);
let quantity = parseInt(quantityElement.textContent);

const selectedLocationCode = localStorage.getItem(‘selectedLocationCode’);

if (selectedLocationCode === ‘METRO-MANILA’) {
// Fetch inventory quantity for Metro Manila before updating the cart
getMetroManilaInventory(variantId).then(availableQuantity => {
if (action === ‘increase’) {
quantity++;
} else if (action === ‘decrease’ && quantity > 1) {
quantity–;
}

updateCart(lineItemId, quantity, lineItemElement, availableQuantity);
});
} else {
alert(“This product is not available for the selected location.”);
}
});
});

document.querySelectorAll(‘.remove-button’).forEach(button => {
button.addEventListener(‘click’, function() {
const lineItemElement = this.closest(‘.line-item’);
const lineItemId = lineItemElement.dataset.lineItemId;

updateCart(lineItemId, 0, lineItemElement);
});
});
});

clipboard_image_9d45d0ab43915a50.png

as far as i know, you cant fetch the inventory level from the frontend. so if you really need inventory count please create a section and use section rendering API to fetch the data, or you can create a JSON object in your product page and read that using JS