I'm making a simple random quote generator. Here is my code so far:
import React from "react";
import "./App.css";
function App() {
const [quote, setQuote] = React.useState({
text: "",
author: "",
});
const [allQuotes, setAllQuotes] = React.useState([]);
React.useEffect(() => {
fetch("https://type.fit/api/quotes")
.then((res) => res.json())
.then((data) => setAllQuotes(data));
}, []);
function getQuote() {
const randomNumber = Math.floor(Math.random() * allQuotes.length);
const text = allQuotes[randomNumber].text;
const author = allQuotes[randomNumber].author;
setQuote((prevQuote) => ({
...prevQuote,
text: text,
author: author,
}));
}
return (
<div className="App">
<p>{quote.text}</p>
<p>{quote.author}</p>
<button onClick={getQuote}>New quote</button>
</div>
);
}
export default App;
The problem is that I do not how to load a page with a quote already. The button works, it's OK but I want to have a quote from the start. I tried different things, like onLoad event:
<div className="App" onLoad={getQuote}>
but it doesn't work.