Returning a random string...button only works once

here’s my code: https://codepen.io/aetones/pen/yLORqbY

I have two arrays which I am trying to return a random string from each. The button seems to be working, but only once. I am not sure how to get it working each time I click the button. If you could suggest what to review to solve this or any hints, thank you!

Your randomNumber value is initialised on page-load, it seems. So the button is working, but always returns the same quote because the random number never changes.

1 Like

Figured that’s what was happening, I am not sure how to update the random number. Could it work doing something similar to this? https://www.freecodecamp.org/learn/front-end-libraries/react/use-state-to-toggle-an-element

You could, I think. I was able to fix it by moving your existing declaration into the click function.

2 Likes

Well, that was an easy fix. Thank you.

1 Like

One more question. I notice it is taking the previous index from the quote and setting it as the current for the author. Why is not using the current index?

handleClick () {
    this.setState({
      quote: theQuotes[ Math.floor(Math.random()*theQuotes.length)],
      author: theAuthors[theQuotes.indexOf(this.state.quote)]
    })
   }

I believe that’s because you’re setting the author by this.state.quote. The change in the state happens all at once, so your this.state.quote is using the current value, not the value that you’re changing to.

I’d ask why you coded the random number into the setState directly, rather than moving the variable declaration into the handleClick function :thinking:

I misunderstood what you meant in your previous fix. I think I got it right this time and it seems to be working.

 handleClick () {
     var randomNumber = Math.floor(Math.random()*theQuotes.length);
    this.setState({
      quote: theQuotes[randomNumber],
      author: theAuthors[randomNumber]
    })
   }
1 Like

That’s the approach I would take! :smiley:

Thanks for walking me through that.

1 Like