I'm getting an error when running the following code that i copied from webdevelopmentcoach on youtube

import React, {Component} from 'react';

import './App.css';

import Button from './components/Button';

import random from 'lodash';

import { render } from '@testing-library/react';

class App extends Component {

  super(props){

  constructor(props)

  this.state =

  {

  quotes : [],

  selectedQuoteIndex : null,

  }

  this.selectQuoteIndex = this.selectQuoteIndex.bind(this);

  }

  componentDidMount()

  {  

  fetch('https://gist.githubusercontent.com/natebass/b0a548425a73bdf8ea5c618149fe1fce/raw/f4231cd5961f026264bb6bb3a6c41671b044f1f4/quotes.json')

  .then(data=>data.json())

  .then(quotes=>this.setState({quotes}))

  .then(()=>this.setState({selectedQuoteIndex:this.selectQuoteIndex()}))

  

  }

  nextQuoteClickHandler()

  {

  console.log("click");

  }

  selectQuoteIndex()

  {

   if (!this.state.quotes.length)

   {

     return;

   }

   return random(0, this.state.quotes.length-1)

  }

  get selectedQuote()

  {

    if (!this.state.quotes.length||!Number.isInteger(this.state.selectQuoteIndex))

    {

      return;

    }

    return this.state.quotes[this.state.selectedQuoteIndex];

  }

  render()

  

  {

    

    return (

      

      <div className="App" id="quote-box">

       

       <Button buttonDisplayName = "next click!"  clickHandler = {this.nextQuoteClickHandler}/> 

       {this.selectedQuote ? this.selectedQuote.quote: ''}

      </div>

  );

  }

}

export default App;

the error in the browser is:

TypeError: Cannot read property ‘quotes’ of null

App.get selectedQuote [as selectedQuote]

C:/Users/admin/random-quote-machine/src/App.js:47

  44 |   {  45 |     //return;  46 |   }> 47 |   return this.state.quotes[0];     | ^  48 | }  49 |   50 | render()

View compiled

App.render

C:/Users/admin/random-quote-machine/src/App.js:58

  55 |       56 |     <div className="App" id="quote-box">  57 |      > 58 |      <Button buttonDisplayName = "next click!"  clickHandler = {this.nextQuoteClickHandler}/>      | ^  59 |      {this.selectedQuote ? this.selectedQuote.quote: ''}  60 |     </div>  61 | );
1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

Please use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks are not single quotes.

markdown_Forums