People help me... Why callback one mehtods in my react component, React proyect

I want my randomQuote () method to start at the beginning of my component.
i try all, but my code display error or not change.
I want to start a new random sentence with the database.

hey @javicoro99,

This is because when calling a fetch it takes some time to bring the data back so the dataB array will be empty on the first run, iv changed up some of your code and added the dataB as state, then call randomQuote after the fetch has completed.

class ComponentRoot extends React.Component {
  constructor(props) {
    this.state = {
      Quote: "",
      Author: "",
      dataB: []
    this.randomQuote = this.randomQuote.bind(this);
  randomQuote() {
    const { dataB } = this.state
    let randomQ = dataB[Math.floor(Math.random() * (1643 - 1) - 1)];
      Quote: randomQ.text,

  async fetchData() {
    const response = await fetch("");
    const data = await response.json();
    return data

  async componentDidMount() {
    const data = await this.fetchData()
    this.setState({dataB: data})
  render() {
    const { Quote, Author } = this.state
    return (
      <div id="quote-box">
        <h2 id="text">{Quote}</h2>
        <i id="author">{Author}</i>
        <br />
            <i class="fab fa-twitter-square"></i>
          <button id="new-quote" onClick={this.randomQuote}>
            NEW QUOTE

ReactDOM.render(<ComponentRoot />, document.getElementById("App"));

1 Like