Hey all. I am trying to set up the random quote machine for the test, but I’m encountering a bug.
I have found a json with the quotes and authors, and I have managed to fetch that data.
function QuoteGenerator(props) {
const [quotes, setQuote] = useState([])
// this containes all quote objects from the JSON
const [quoteIndex, setQuoteIndex] = useState(1)
// this sets the index within the "quotes" array
const selectedQuote = quotes[quoteIndex]
//this selects the quote object within the quotes array at the quoteIndex. Everything works fine so far
const [currQuote, setCurrQuote] = useState("")
function randomNumber(min, max) {
let random = Math.random() * (max - min) + min;
return Math.round(random)
}
useEffect(() => {
fetch("https://gist.githubusercontent.com/natebass/b0a548425a73bdf8ea5c618149fe1fce/raw/f4231cd5961f026264bb6bb3a6c41671b044f1f4/quotes.json")
.then(data => data.json())
.then(quotes => (setQuote(quotes )),
)
}, []);
let handleClick = () => {
setQuoteIndex(randomNumber(1, 101))
}
console.log(selectedQuote)
// const quoteText = selectedQuote.quote
// THIS IS THE BUG. When I console log selectedQuote, it works fine. As soon as I try to access either the "quote" or "author" properties within the quote, I get the error.
The bug is that while I can get the object from the JSON that contains the quote and the author, I can not access either properties within the object. When I try to access these properties (selectedQuote.quote, or selectedQuote.author), I get the error “cannot read property ‘quote’/‘author’ of undefined”.
Can someone help explain to me what I’m doing wrong here?
Quote machine bug - CodeSandbox I have put it up on codesandbox. I also used the better random number generator that @caryaharper showed me.
Another thing I noticed, if I try to get the quote or author property after the app has already loaded, I can do it. However, if I try to get the properties while loading the app, it gives me the error again.