I’m creating a random quotes generator but there’s a problem. It just doesn’t generate a random quote at the beginning. Please correct me so that the generate random quote works at least one time when rendering
const [quotes, setQuotes] = useState([]);
const [randomQuote, setRandomQuote] = useState();
useEffect(() => {
async function fetchData() {
await fetch(process.env.NEXT_PUBLIC_API_URL)
.then(res => res.json())
.then(data => setQuotes(data))
.catch(err => console.error(err));
}
fetchData();
console.log('from useEffect', quotes);
generateRandomQuote();
}, []);
console.log('After useEffect(): ', quotes);
const generateRandomQuote = () => {
const randomIndex = Math.floor(Math.random() * quotes.length);
const selectedQuote = quotes[randomIndex];
setRandomQuote(selectedQuote);
};
3
Answers
try this :
You don’t have to define the function fetchData inside the useEffect() that’s kind of odd.
Secondly the fetchData seems to be an async function but you are not awaiting it.
or
Do not use
then
withasync/await
.use either one but not both at once.