score:2

The problem is that in the randomQuoteHandler you are replacing the whole array of quotes with the random randomQuote object. The log at the end of this randomQuoteHandler function is showing that.

this.setState({
  quotes: randomQuote  // Array get replaced by one object
});

therefore the second time there is no array in the sate to read this.state.quotes.quote

score:2

The randomQuoteHandler replaces this.state.quotes array with a chosen quote which is an object. So on the second click, this.state.quotes.length is undefined.

You need to store the chosen quote in another state variable like randomQuote.

class App extends React.Component {
  state = {
    quotes: null,
    randomQuote: null,
  }
  componentDidMount() {
    fetch(
      'https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json',
    )
      .then(res => res.json())
      .then(data => {
        // console.log(data);
        this.setState({
          quotes: data.quotes,
        })
      })
    // console.log(this.state.quotes);
  }
  randomQuoteHandler = () => {
    const randNumb = Math.floor(Math.random() * this.state.quotes.length)
    const randomQuote = this.state.quotes[randNumb]
    this.setState({
      randomQuote: randomQuote,
    })
    console.log(this.state.quotes)
  }
  render() {
    return (
      <div>
        <button onClick={this.randomQuoteHandler}>gen</button>
        <p>{this.state.randomQuote !== null && this.state.randomQuote.quote}</p>
        <p>{this.state.randomQuote !== null && this.state.randomQuote.author}</p>
      </div>
    )
  }
}

Related Query

More Query from same tag