Random Quote Machine React ComponentDidMount not updating state

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

Do you have a codepen for this project?
I am not very good a debugging unless I can mess with the code

One thing you could improve on here, though, is simply reusing your changeQuote() function in the componentDidMount() method since they are executing the same logic

e.g.

ComponentDidMount() {
    changeQuote();
}

This way you dont have to maintain two calls to the API should it change, it is also less code and more readable. I don’t think this will fix your issue but is a good refactor nonetheless :slight_smile:

Thanks for the tip I will definitely try that! Here is the codepen: https://codepen.io/sportinguista/pen/EONoyV/

oh its just a typo

ComponentDidMount() => componentDidMount()

:+1:

1 Like

Can’t believe I missed that :see_no_evil: Thank you!

1 Like