简体   繁体   中英

How do I fetch data from an endpoint everytime I click a button? In React

This is my first question on StackOverflow! :D So, I am trying to learn React and I have to do an app that generates random quotes when a button is clicked. I have a problem when trying to get data from an API and passing it to the state of the component. I searched the internet but all I could found was that in React, most API calls are made inside componentDidMount , but that doesn't help at all. I need to make a call to the endpoint everytime the button is clicked. Edit: I have to mention that I am using codepen.io for this. Maybe the problem is related to this. Here is the link ( https://codepen.io/bogdanoprea1998/pen/abWmaWa?editors=0011 )

const setRandomColor = () => {
  const color =
    "hsl(" +
    360 * Math.random() +
    "," +
    (25 + 70 * Math.random()) +
    "%," +
    (85 + 10 * Math.random()) +
    "%)";
  $("#quote-box").css("background-color", color);
};

class QuoteApp extends React.Component {
  constructor() {
    super();
    this.state = {
      author: "Satya Nadella",
      quote: "This is a software-powered world.",
    };
    this.handleClick = this.handleClick.bind(this);
  }

  //Handlers
  handleClick() {
    fetch("http://quotable.io/random")
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        this.setState((prevState) => {
          return {
            author: data.author,
            quote: data.content,
          };
        });
      });
    setRandomColor();
  }

  componentDidMount() {
    fetch("http://quotable.io/random")
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        this.setState((prevState) => {
          return {
            author: data.author,
            quote: data.content,
          };
        });
      });
    setRandomColor();
  }
  //Error handling
  componentDidCatch(error, errorInfo) {
    console.log(error, errorInfo);
  }

  render() {
    const tweetLink = `https://twitter.com/intent/tweet?text=${this.state.quote} -${this.state.author}`;
    return (
      <div id="quote-box">
        <h2 id="text">{this.state.quote}</h2>
        <h3 id="author">{this.state.author}</h3>
        <a className="twitter-share-button" href={tweetLink} id="tweet-quote">
          Tweet
        </a>
        <button onClick={this.handleClick} id="new-quote">
          Next
        </button>
      </div>
    );
  }
}

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

I've tried your code, and the code looks good. I believe the issue is with the API URL that you use. Try to use this instead https://api.quotable.io/random . It will work now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM