-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
48 lines (43 loc) · 1.6 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/** @format */
const adviceQoute = document.querySelector(".advice-qoute");
const adviceId = document.querySelector(".advice-id");
const newAdviceBtn = document.querySelector(".new-advice-btn");
// add event listener for trigerring change of advice
newAdviceBtn.addEventListener("click", fetchNewAdvice);
// functions
function fetchNewAdvice() {
// Call `fetch()`, passing in the URL.
fetch("https://api.adviceslip.com/advice")
// fetch() returns a promise. When we have received a response from the server,
// the promise's `then()` handler is called with the response.
.then((response) => {
// Our handler throws an error if the request did not succeed.
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
// Otherwise (if the response succeeded), our handler fetches the response
// as a JavaScript object by calling response.json(), and immediately returns the promise
// returned by `response.json()`.
else {
// console.log(response.json());
return response.json();
}
})
// When response.json() has succeeded, the `then()` handler is called with
// the object, and we assign it as the value of the `adviceSlipObject` variable.
.then((slipObject) => {
updateNewAdvice(slipObject.slip.id, slipObject.slip.advice);
})
// Catch any errors that might happen, and display a message
// .
.catch((error) => {
console.log(error);
});
}
function updateNewAdvice(id, advice) {
// update the text contents of the affected elements
adviceId.textContent = id;
adviceQoute.textContent = advice;
}
// show new advice on page load finish
fetchNewAdvice();