Hi everyone,
I am currently on the Random Quote Machine Project. I am using React. At the moment I am simply trying to ensure that a quote which gets fetched from an API is displayed on first load. The new quote button is working fine but I’m having trouble getting this part of the project to work. I have tried inserting the code in a callback within setState and also checking if state has updated in the render method (as setState is asynchronous) but have not had much luck. I have also tried logging the data object to the console within setState but nothing gets logged.
Any help would be appreciated.
Here is my code and a link to the codepen:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
quote: '',
author: ''
}
this.changeQuote = this.changeQuote.bind(this);
}
ComponentDidMount() {
fetch('https://talaikis.com/api/quotes/random/')
.then(results => results.json())
.then(data =>
this.setState({
quote: data.quote,
author: data.author
}))
}
changeQuote() {
fetch('https://talaikis.com/api/quotes/random/')
.then(results => results.json())
.then(data =>
this.setState({
quote: data.quote,
author: data.author
}))
}
render() {
return (
<div>
<h3 id='text'>{this.state.quote}</h3>
<p id='author'>- {this.state.author}</p>
<button id='new-quote' onClick={this.changeQuote}>New Quote</button>
<button><a id='tweet-quote' href='#'>Tweet</a></button>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('quote-box'));