2
In this code I access a fake Rest api, I take the data, step for json, but when it comes to presenting the cards of the users I cannot find a good way to do this, innerHTML erases all the cards and only presents the last one.
please answer in js vanila, but if there is no other way...
and already taking advantage of which safety care I have to take in these cases ?
var button = document.getElementById('load');
button.onclick = async function () {
/* fake api */
const url = "https://reqres.in/api/users?page=2";
const elementsArray = document.querySelectorAll(".card-container");
const containerEl = document.querySelector(".container");
await fetch(url)
.then((resp) => resp.json()
.then(function(myJson){
const data = myJson.data;
/* para cada item cria um card novo na tela */
data.forEach((item)=>{
containerEl.innerHTML =
'<div class="card-container">'+
'<img src="'+item.avatar+'" class="card-img"/>'+
'<h3 class="card-title">'+
item.first_name +
'</h3>'+
'<p card-text>'+
item.email+
'</p>'+
'</div>';
})
})
)
};
body, html{
margin: 0;
padding: 0;
}
.container{
display: flex;
flex-direction: column;
flex: 1;
align-items: center;
padding: 10vh 0;
}
.card-container{
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 5vh;
margin-top: 15px;
padding: 10px;
background: #eee;
}
.card-container:hover{
cursor: pointer;
box-shadow: 0 0 5px #888;
}
<div class="container">
<!-- BUTTON TO LOAD CONTENT -->
<button id="load" type="button">Load all contents</button>
<!-- CARD 1 -->
<div class="card-container">
<img src="https://visualsound.com/wp-content/uploads/2019/05/unavailable-image.jpg" width="200px" class="card-img"/>
<h3 class="card-title">
TITULO
</h3>
<p card-text>
alguma informação referente a imagem.
</p>
</div>
<!-- CARD 2 -->
<div class="card-container">
<img src="https://visualsound.com/wp-content/uploads/2019/05/unavailable-image.jpg" width="200px" class="card-img"/>
<h3 class="card-title">
TITULO
</h3>
<p card-text>
alguma informação referente a imagem.
</p>
</div>
<!-- CARD 3 -->
<div class="card-container">
<img src="https://visualsound.com/wp-content/uploads/2019/05/unavailable-image.jpg" width="200px" class="card-img"/>
<h3 class="card-title">
TITULO
</h3>
<p card-text>
alguma informação referente a imagem.
</p>
</div>
</div>
great guy, answered my question very quickly and simple :) thank you
– leonardo vita