Random Quote Machine challenge - not loading first quote

Tell us what’s happening:
Hello everyone, I managed to make most of the main behaviour to work.
When I click the New Quote button, a new quote comes.
However, I am struggling to load the first quote.

I divided my code in two main functions


to call the API and bring the quotes. And


To bring a new random quote whenever the button is clicked.

My plan was to call getQuotes() on the componentDidMount(), and then, immediately after, call getNewQuote(), to bring the first random quote.

The call to getQuotes() is working as I expected. But the call to getNewQuote() is not.
Please uncomment the line in the code so you can see what is happening.

Your code so far

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:101.0) Gecko/20100101 Firefox/101.0

Challenge: Build a Random Quote Machine

Link to the challenge:

I’ve tried another variation with componentDidUpdate().
Giving a different error:

You can’t call getNewQuote inside componentDidUpdate because getNewQuote sets state which causes a an update (re-render) which triggers componentDidUpdate, which in turn calls getNewQuote and so on and so forth.

Inside getQuotes, call getNewQuote inside the last .then() after the state update.

As an aside, the two arguments to the setState updater function is state and props. Naming the props argument randomIndex doesn’t change that fact and is just confusing, especially when you have an outer variable named the same. The props argument is just an empty object anyway in this case, as there are no props.

Setting the index and using it in the same setState call also reads a little confusing. The way you have it set up means the initial quote is always the same (initial state value of indexQuote). I would rename or remove the props argument and use the randomIndex variable you are assigning a random index to in the outer scope instead.

That’s awesome @lasjorg! Thanks for the clear explanation and also thank you also for observing the indexQuote thing. Indeed, there were some leftovers of the things I was trying.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.