Hello all,
I’m trying to complete Project 1 of the Front End Libraries using React only. I am able to read quotes programatically and update them in the state, but then when I try to render them I’m getting ‘TypeError: Cannot read property ‘quote’ of undefined’, but when I do not render the quotes object, I can see it is being captured in the state as an object with no issues.
So I’m confused with this behaviour on why when I try to render it is undefined, but when I don’t render it, state in the console shows good.
Below is what I get when I don’t render the state:
Other funny thing is that I’m logging the type of the quotes in the state, and I’m getting to logs even though I print it once, on one line I get type String, and on the second one I get Object, why would that be?
Code below:
class Quote extends React.Component{
constructor(props){
super(props);
this.state = {
msg: '',
randomIndex: 0
};
this.changeQuote = this.changeQuote.bind(this);
}
changeQuote(){
}
componentDidMount() { fetch('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json', {
headers : {
'Accept': 'application/json'
}
})
.then(response => response.json())
.then(data => this.setState({msg:(data.quotes)}));
}
render() {
const quotes = this.state.msg
console.log(typeof(quotes));
return(
<div>
<button onClick = {this.changeQuote}>Change Quote</button>
<p>{quotes[0]['quote']}</p>
</div>
)}
}
ReactDOM.render(<Quote/>, document.getElementById('root'));
Any help is greatly appreciated, I already tried everything, googled multiple times but I can’t get it to render a quote from the state.
Thanks!
Kevin