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 | );