Browse Source

promises finalized

16-media_queries
senne 4 years ago
parent
commit
7d74a66749

+ 2
- 0
15-promises/fetch/index.html View File

@@ -12,6 +12,8 @@
<button id="get-endpoints-btn">Get endpoints</button>
</div>
<div id="endpoint-container"></div>
<div id="result-container"></div>
<div id="detail-container"></div>

<script src="scripts/main.js"></script>
</body>

+ 75
- 2
15-promises/fetch/scripts/main.js View File

@@ -1,5 +1,7 @@
const endpointContainer = document.getElementById('endpoint-container');
const getEndpointsBtn = document.getElementById('get-endpoints-btn');
const resultContainer = document.getElementById('result-container');
const detailContainer = document.getElementById('detail-container');

function getEndpoints() {
@@ -39,7 +41,7 @@ function makeRequest(event) {
let btnText = btn.innerHTML;
btn.innerHTML = 'loading...';

let request = new XMLHttpRequest();
/* let request = new XMLHttpRequest(); zelfde als fetch!!!!

request.addEventListener('load', function(event) {
if (event.target.status === 200) {
@@ -53,9 +55,80 @@ function makeRequest(event) {
});

request.open('GET', event.target.dataset.url);
request.send();
request.send(); */

fetch(event.target.dataset.url)
.then(function(response){
if(response.ok){
return response.json();
}
return Promise.reject(new Error('request failed'));
})
.then(function(jsonResponse){
btn.innerHTML = btnText;
console.log(jsonResponse);
resultContainer.innerHTML = printList(jsonResponse.results); //toevoegen van results
})
.catch(function(error){
console.error(error);
btn.innerHTML = 'dikke fail...';
});
}
}

function printList(list){
return list.reduce(function(html,listItem){
return `
${html}
<article class= "list-item">
<p> ${listItem.name? listItem.name:listItem.title}</p>
<button data-url= "${listItem.url}">Show Detail</button>
</article>
`;

}, '');
}
function listDetails(details){
return Object.keys(details).reduce(function(html, detailKey){
return `
${html}
<p>
<strong>${detailKey}:</strong>${details[detailKey]}
</p>
`;
}, '');
}

function requestDetails(event){
if (event.target.matches('button')) {
let btn = event.target;
let btnText = btn.innerHTML;
btn.innerHTML = 'loading...';

fetch(event.target.dataset.url)
.then(function(response){
if(response.ok){
return response.json();
}
return Promise.reject(new Error('request failed'));
})
.then(function(jsonResponse){
btn.innerHTML = btnText;
console.log(jsonResponse);
detailContainer.innerHTML = listDetails(jsonResponse);
})
.catch(function(error){
console.error(error);
btn.innerHTML = 'dikke fail...';
});
}
}

getEndpointsBtn.addEventListener('click', getEndpoints);
endpointContainer.addEventListener('click', makeRequest);
resultContainer.addEventListener('click',requestDetails);

+ 4
- 0
15-promises/fetch/styles/main.css View File

@@ -26,3 +26,7 @@ button {
margin: 0.5rem 0;
padding: 0.6rem 2rem;
}
article {
display: flex;
justify-content: space-between;
}

Loading…
Cancel
Save