Hello!
I am getting a ‘TypeError: cannot read property quote of undefined’
I know that the ‘quotes’ array in this.state is undefined, but not sure how to fix.
Can someone help me?
Thanks!
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
apiResult: null,
author: "",
quotes: [],
text: "",
isLoaded: false,
bgColor: "#f99192",
number: 0,
clickCount: 0
};
this.generateRandomNumber = this.generateRandomNumber.bind(this);
}
componentDidMount() {
fetch(
"https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json"
)
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
quotes: json
});
});
}
generateRandomNumber(quotes) {
this.setState({
number: Math.floor(Math.random() * quotes.length)
});
}
render() {
var { quotes, isLoaded } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div id="quote-box">
<h1 id="text">{quotes.quotes[this.state.number].quote}</h1>
<p id="author">{quotes.quotes[this.state.number].author}</p>
<button
id="new-quote"
className="btn btn-secondary"
onClick={this.generateRandomNumber}
>
New Quote
</button>
<a
id="tweet-quote"
className="btn btn-primary"
href="twitter.com/intent/tweet"
role="button"
>
Tweet Quote
</a>
</div>
);
}
}
}
export default App;