I'm trying to display two images on the browser based on url's I got from an API.
So,
HTML:
<body>
<button id="new-deck">New Deck, Please!</button>
<button id="draw-cards">Draw</button>
<script src="index.js"></script>
<div id="container-card"></div>
</body>
JS:
let deckId
let container = document.getElementById('container-card')
function handleClick() {
fetch("https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1")
.then(res => res.json())
.then(data => {
console.log(data)
deckId = data.deck_id
})
}
document.getElementById("new-deck").addEventListener("click", handleClick)
document.getElementById("draw-cards").addEventListener("click", () => {
fetch(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=2`)
.then(res => res.json())
.then(data => data.cards.map(item =>container.innerHTML += `<img src=${item.image}/>`))
})
There are two issues:
deckId during image fetch api call.src url must be enclosed into quotes, otherwise backslash is added to the end of the url: let deckId
let container = document.getElementById('container-card')
function handleClick() {
fetch("https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1")
.then(res => res.json())
.then(data => {
console.log(data)
deckId = data.deck_id
})
}
document.getElementById("new-deck").addEventListener("click", handleClick)
document.getElementById("draw-cards").addEventListener("click", () => {
fetch(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=2`)
.then(res => res.json())
.then(data => data.cards.map(item =>container.innerHTML += `<img src="${item.image}"/>`))
})
<button id="new-deck">New Deck, Please!</button>
<button id="draw-cards">Draw</button>
<script src="index.js"></script>
<div id="container-card"></div>
Every time you are dealing with API calls, make sure you check what data you receive before you minimalistic your code with one-liners.
and use catch for promises to catch any errors that might occur.