Random Quote Machine: Object handling

I’m tearing my hair out a little as I clearly don’t understand why I’m coming up against object errors.
When I console.log(this.state.quotesData) it appears to show an array of objects.
However, when I then try const possibleQuotes=this.state.Quotesdata (as opposed to the dummy numerical array in the code below), it just throws me object errors, telling me that objects cannot be passed as React children. I’m not trying to pass objects, but an array of objects!
Also, how do I circumvent the issue which occurs as the component first renders (before fetching the data), thus returning an empty array and causing the render to throw errors too (i.e. nextQuote.author)?
When I console.log(this.state.quotesData), it logs as an empty array and then as an array of objects.

class RandomQuotes extends React.Component {
  constructor(props) {
    this.state = {
      random: Math.random(),
      quotesData: [],
      isFetching: false
    this.getNewQuote = this.getNewQuote.bind(this);
    this.fetchUsers = this.fetchUsers.bind(this);
  fetchUsers() {
    this.setState({isFetching: true});
   fetch ('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json', {headers: {
      Accept: 'application/json'
      .then(res => res.json())
      .then((data) => 
      this.setState({quotesData: data.quotes, isFetching: false});
    .catch(e => {
                this.setState({isFetching: false});
  getNewQuote() {
      random: Math.random()

  componentDidMount() {

  render() {
    const possibleQuotes = [1, 2, 3, 4, 5, 6];
    const randomIndex = Math.floor(this.state.random * possibleQuotes.length);
    const nextQuote = possibleQuotes[randomIndex];
    const nextQuoteAuthor = nextQuote.author;
    const nextQuoteQuote = nextQuote.quote;
    return (
      <div id="quote-box">
        <p id="text">{nextQuoteQuote}</p>
        <p id="author">{nextQuoteAuthor}</p>
        <button id="new-quote" onClick={this.getNewQuote}>
          New Quote

ReactDOM.render(<RandomQuotes />, document.getElementById("root"));

guy, have you solved this problem?

Yes, thank you. I realised that I needed conditional rendering to make it work.
The working pen is here: https://codepen.io/igorgetmeabrain/pen/rNmwMEM

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.