I am fetching a quotes API. Here I want to update the quotes randomly but I want to update the quotes on button click. I have no idea how to do that. Can anyone help me to do so?
I have fetched data using fetch request then add data to state.
This is my code
import React from "react";
import "./styles.css";
class Box extends React.Component {
constructor(props) {
super(props);
this.state = {
quote: "",
author: ""
};
}
componentDidMount() {
this.fetchData();
}
fetchData = () => {
fetch(
"https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json"
)
.then(result => {
return result.json();
})
.then(data => {
const ran = Math.floor(Math.random() * data.quotes.length);
console.log(data.quotes[ran].quote);
console.log(data.quotes[ran].author);
this.setState({
quote: data.quotes[ran].quote,
author: data.quotes[ran].author
});
});
};
render() {
return (
<div id="quote-box" className="container">
<div className="box-container">
<div className="text-center">
<h1 id="text">{this.state.quote}</h1>
</div>
<div className="float-right">
<p id="author">
<span>- </span>
{this.state.author}
</p>
</div>
</div>
<div className="box-item">
<div className="row">
<div className="col-sm-6">Twitter</div>
<div className="col-sm-6">
<button>next quote</button> <--- Here i want this button to update quotes on screen.
</div>
</div>
</div>
</div>
);
}
}
export default Box;