Hello! I am working on the Random Quote machine portfolio project:
https://learn.freecodecamp.org/front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine
My tweet link functions perfectly after the New Quote button has been clicked, but on load is empty, even though there is a quote being shown.
Here is the component in charge of that:
class QuoteBox extends React.Component {
constructor(props) {
super(props);
this.state = {
quotes: [["Your time is limited, so don't waste it living someone else's life.", "Steve Jobs"], ["I am not a product of my circumstances. I am a product of my decisions.", "Stephen Covey"], ["If you do what you've always done, you'll get what you've always gotten", "Tony Robbins"]],
newQuote: "",
newAuthor: "",
tweetLink: ""
}
this.getQuote = this.getQuote.bind(this);
}
componentWillMount() {
this.getQuote();
}
getQuote() {
let randomIndex = Math.floor(Math.random()*this.state.quotes.length);
this.setState({
newQuote: this.state.quotes[randomIndex][0],
newAuthor: this.state.quotes[randomIndex][1],
tweetLink: "https://twitter.com/intent/tweet?text=" + "'" + this.state.newQuote + "' -" + this.state.newAuthor
});
}
render() {
return (
<div id="quote-box">
<h2>Quote Machine</h2>
<QuoteText quote={this.state.newQuote} author={this.state.newAuthor}/>
<button id="new-quote" onClick={this.getQuote}>New Quote</button>
<a id="tweet-quote" href={this.state.tweetLink} target="_blank">Tweet</a>
</div>
);
}
};
Edit: I was trying to access the newQuote and newAuthor thinking they would update before tweetLink but it looks like they all update at once. I changed this.state.newQuote and this.state.newAuthor to match this.state.quotes[randomIndex][0] and [1] respectively and it fixed the problem:
getQuote() {
let randomIndex = Math.floor(Math.random()*this.state.quotes.length);
this.setState({
newQuote: this.state.quotes[randomIndex][0],
newAuthor: this.state.quotes[randomIndex][1],
tweetLink: "https://twitter.com/intent/tweet?text=" + "'" + this.state.quotes[randomIndex][0] + "' -" + this.state.quotes[randomIndex][1]
});