Skip to content

Instantly share code, notes, and snippets.

@drinkmorewaters
Last active May 20, 2020 06:03
Show Gist options
  • Save drinkmorewaters/bbb2367a9af764f7c53d42c318ae5118 to your computer and use it in GitHub Desktop.
Save drinkmorewaters/bbb2367a9af764f7c53d42c318ae5118 to your computer and use it in GitHub Desktop.
Shopify savings calculator ASYNC AWAIT
// Async Await version, although, i am not sure it's made things easier
(async () => {
// Change the domain name
try {
const fetchIt = await fetch(`${window.location.origin}/cart.js`)
const response = await fetchIt.json()
const data = response
const loopOver = data.items.map((d) => {
let handleURL = `${window.location.origin}/products/${d.handle}.js`
return handleURL
})
loopOver.map(async url => {
try {
const fetchIt = await fetch(url)
const response = await fetchIt
const data = await response.json()
.then(data => {
let compare = data.compare_at_price / 100
let price = data.price / 100
if (compare != null && compare > 0) {
// Remove minus sign
let savings = Math.abs(price - compare)
let finalText = `You saved $${savings.toFixed(2)}!`
// Change this to suit your store
let finalSavings = document.querySelector('.drawer__footer')
let newDiv = document.createElement('div')
let newP = document.createElement('p')
newP.innerHTML = `${finalText}`
newDiv.appendChild(newP)
newDiv.style = "display: flex; justify-content: center;"
finalSavings.appendChild(newDiv)
}
})
} catch (e) {
console.log(e)
}
})
} catch (e) {
console.log(e)
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment