Last active
May 20, 2020 06:03
Shopify savings calculator ASYNC AWAIT
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
// 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