Skip to content

Instantly share code, notes, and snippets.

@tpage99
Last active August 8, 2023 07:13
Show Gist options
  • Save tpage99/209553da6303b8bc625435586c67e43e to your computer and use it in GitHub Desktop.
Save tpage99/209553da6303b8bc625435586c67e43e to your computer and use it in GitHub Desktop.
Cart API Frequently Used - Vanilla JS
// Always compare to the docs first: https://shopify.dev/docs/api/ajax/reference/cart
// Get the Cart
fetch("/cart.js")
.then((response) => response.json())
.then((data) => console.log(data));
// Add to Cart
let addToCartItem = {
items: [
{
id: varID,
quantity: 1,
properties: {
'Cart line item property': 'Standard',
'__Cart line item property': 'Hidden' // item is hidden due to prefacing with double underscore
}
}
]
}
async function addToCart(){
let response = await fetch(`/cart/add.js`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(addToCartItem)
})
if(!response.ok) {
throw new Error(`Something is up! Status: ${response.status}`);
}
else {
console.log(`${addToCartItem} added to the cart`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment