Please assist: My react random quote machine does not generate random quote on page load

HI ,
Please could someone assist. I am completing the random quote machine project, using react on visual studio code IDE and so far, I have gotten the machine to generate a new quote for every button click, but I currently have the challenge that it does not load a random quote on page load or refresh.

I have searched endlessly on the forum for a solution to the problem, one particular solution as stated on this forum link : link, involved the use of jquery to trigger the onClick handler of the quote button , but when I tried it, it didn’t do anything for my problem. My code is stated below.

React/Javascript code:

class App extends Component {

  constructor(props){

    super(props);

    this.state = {

      quotes: [],

      text: "",

      author: ""

    }

    this.handleClick= this.handleClick.bind(this);

  }

 

  componentDidMount(){

    axios.get("https:type.fit/api/quotes")

      .then(res => {

        console.log(res);

        this.setState({

          quotes: res.data

        });

      })

      

  }

  handleClick() {

    //const { quotes } = this.state.quotes;

    var randIndex = Math.floor(Math.random() * this.state.quotes.length);

    this.setState({

      text: this.state.quotes[randIndex].text,

      author: this.state.quotes[randIndex].author

    });

  }

  render() {

    return (

      <div id= "quote-box">

       <Quotation text = {this.state.text} author= {this.state.author} />

       <button id= "new-quote" onClick= {this.handleClick}>New Quote</button>

      </div>

    )

  }

}

const Quotation = (props) => {

  return (

    <div>

     <blockquote>

      <h2 id= "text">"{props.text}</h2>

      <footer id= "author">{props.author}</footer>

     </blockquote>

    </div>

  )

}

My jquery code:

$( document ).ready(function(){

        $( "#quote-box" ).click();

        

      });

Please any assistance would be greatly appreciated. Thanks in anticipation.

First: Using React together with jQuery is a bad practice.

Second: You have a typo in fetch url (missing //).

Third: setStatetakes a function as second parameter, which is called after state is updated. So you need to add the function in setState in componentDidMount.

Here’s an example:

Thanks so much for the assistance, as it has helped me resolve the issue. Also, by the way , do you know why it was never mentioned in the several places setState was used in the FCC curriculum, that it can take two arguments?

No I do not, but it’s mentioned in the React docs: https://reactjs.org/docs/react-component.html#setstate