I need to display random quote from API using React hooks useState and useEffect.
import React, { useState, useEffect } from "react";
const API =
"https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json";
const App = () => {
const [quote, setQuote] = useState({
quotes: [],
index: 0,
});
useEffect(() => {
fetch(API)
.then((res) => {
return res.json();
})
.then((quote) => {
setQuote(quote);
console.log(quote.quotes[0].quote); // prints quote
console.log(quote.index); // prints undefined
});
}, []);
const getRandomIndex = () => {
setQuote((previosState) => {
return {
...previosState,
index: Math.floor(Math.random() * quote.quotes.length),
};
});
};
return (
<>
<p>this is quote: "{quote.quotes[index]}"</p>
</>
);
};
export default App;
In the useEffect hook it prints correct quote, but it prints undefined for index.
Could you help me to print random quote here
<p>this is quote: "{quote.quotes[index]}"</p>
after index was randomly generated.