Tell us what’s happening:
context
Hello, I am trying to make the random quote machine project using functional components in React. I would like to load the quotes only once (when the page loads), then just select from the data when the button is pressed. Using class components I would utilize the didcomponentmount method. When using functional components, from what I can tell the useEffect() method is used in place of all the mounting/unmounting stuff.
The Problem
on the initial page load, the default quote value of “EMPTYQUOTE” is shown. From what I can tell, this is because the 3rd ‘.then’ function executed before the prior one has set the quote data. I would guess that this is because the setQuoteData method doesn’t have a callback that can be passed to the 3rd ‘.then’ function. When I log the console for data here it returns nothing as in a blank line in the console. How can I make the quote show on the initial page load using React?
Your code so far
function QuoteMachine(props){
const[quote, setQuote] = useState("EMPTY QUOTE")
const[author, setAuthor] = useState("author")
const[quoteData, setQuoteData] = useState('')
const newQuote = () =>{
let randIndex = Math.floor(Math.random() * quoteData.length)
let randQuote = quoteData[randIndex]
console.log(quoteData)
setQuote(randQuote.quote)
setAuthor(randQuote.author)
}
useEffect(() => {
const Data = "https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json";
const response = fetch(Data)
.then((response) => response.json())
.then((data) => {
setQuoteData(data.quotes)
console.log("1")
})
.then(() => {
newQuote()
})//^^HERE
}, [])
return (
<div className = "quote-project">
<div id ='quote-box' className = "quote-box">
<div className="just-quote">
<h2 id = 'text'>{quote}</h2>
</div>
<h3 id = 'author'>~ {author}</h3>
<button id = 'new-quote' onClick = {newQuote}>New Quote</button>
<a id = 'tweet-quote' href="twitter.com/intent/tweet"><i className="fab fa-twitter"></i></a>
</div>
</div>
)
}
function MarkdownPreviewer(props){
return(
<div className = "markdown-previewer">
</div>
)
}