Random Quote Machine in React, need help

Tell us what’s happening:
My questions:

  1. How can I add animations that triggers when clicked on button?
  2. How can I import and use JSON files for quotes?
  3. How can I fix the tweet button so it tweets the current quote but not the previous one?

Your code so far

https://codepen.io/ozanbaskan/pen/QWKXjJy

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36.

Challenge: Build a Random Quote Machine

Link to the challenge:

  1. I’m not sure, that would probably take some library.

  2. If you were building this locally, it would be trivial to include a json file at build time. At runtime it gets a little more complicated, but is still doable, you just need to fetch that file. Since this is codepen, you’ve have to store it somewhere else. The last option would be to make a request to an http service to get the data.

  3. I don’t have time at the moment to dig into it, but this raises alarm bells:

  this.state.tweetLink = "https://twitter.com/intent/tweet?text=" + encodeURIComponent('"' + currentQuote + '" ' + currentAuthor);

Never mutate state directly. Always call setState. When you mutate state directly, a puppy dies. And more importantly, React gets confused and doesn’t rerender the way you want. The other problem is that a few lines above, you are setting state. But setting state is asynchronous so you have no idea if it will finish before:

    let currentQuote = this.state.quote;
    let currentAuthor = this.state.author;

So, you don’t know if those will be the old values or the new ones. You should get those values elsewhere, or, better yet, compile all the data and make one setState call for both.

2 Likes