Last active
August 8, 2023 07:13
-
-
Save tpage99/209553da6303b8bc625435586c67e43e to your computer and use it in GitHub Desktop.
Cart API Frequently Used - Vanilla JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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