Issue
I'm trying to build a page that displays a random quote with a <button>
that changes the quote for each click.
This is the async function:
let quote, author;
async function getData() {
const response = await fetch('https://type.fit/api/quotes');
const data = await response.json();
const random = await data[Math.floor(Math.random() * data.length)];
quote = random.text;
author = random.author;
}
getData()
works I can log author
and quote
into it, but I can't use the returned value outside of the function. I know that async function
always returns a Promise
so I have to use .then
but I have to write new functions that use the data retrieved by getData()
as:
function foo(quote, author){
....do stuff
}
The new function must modify the HTML code to change author
and quote
. The only solution that came to my mind is to create a function that contains everything (a huge chain of .then
) and then pass it to the <button>
via onclick
. But it seems like a stupid and chaotic thing, and it wouldn't be a Promise
anyway since it's the result of .then
?
Solution
You can create author
and quote
variable in the function to re-decalre them every time when function is called
cosnt {quote, author} = data[randomNumber]
in here you grab quote
and author
keys in the called data
every onClick these variable will be re-decalread and you will be able insert them as DOM Element innerHTML
You can check my solution How I would do that
const quoteText = document.querySelector("h1")
const authorText = document.querySelector("p")
const btn = document.querySelector("button")
async function grabNewQuote(){
const response = await fetch("https://type.fit/api/quotes")
const quotes = await response.json()
let randomNumber = Math.floor(Math.random() * quotes.length)
//Math.floor() -> rounds the number to down if random number is
//3.99 it will output 3
//Math.random() randomly picks up number between length size and 0
const {text, author} = quotes[randomNumber]
quoteText.innerHTML = text
authorText.innerHTML = author
}
btn.addEventListener("click", grabNewQuote)
<h1><h1>
<p></p>
<button>New Quote 🎉</button>
Also you could use .then
but it would make big mess in the code and it would be less readable
if you are comfortable with .then()
you can replace that following code up there
await fetch("https://type.fit/api/quotes")
.then(response => response.json())
.then(quotes = > {
let randomNumber = Math.floor(Math.random() * quotes.length)
const {text, author} = quotes[randomNumber]
quoteText.innerHTML = text
authorText.innerHTML = author
})
Answered By - callmenikk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.