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.
https://codepen.io/javicoro99/pen/yLayojR
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) {
    super(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)];
    this.setState({
      Quote: randomQ.text,
      Author: randomQ.author
    });
  }

  async fetchData() {
    const response = await fetch("https://type.fit/api/quotes");
    const data = await response.json();
    return data
  }

  async componentDidMount() {
    const data = await this.fetchData()
    this.setState({dataB: data})
    this.randomQuote();
  }
  render() {
    const { Quote, Author } = this.state
    return (
      <div id="quote-box">
        <h2 id="text">{Quote}</h2>
        <i id="author">{Author}</i>
        <br />
        <div>
          <a
            id="tweet-quote"
            href={`https://twitter.com/intent/tweet?text="${this.state.Quote}"%20-%20${this.state.Author}%20@javicoro99`}
            target="_top"
          >
            <i class="fab fa-twitter-square"></i>
          </a>
          <button id="new-quote" onClick={this.randomQuote}>
            NEW QUOTE
          </button>
        </div>
      </div>
    );
  }
}

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

1 Like