I'm trying to understand functional components and hooks. There is a component which download array of Quotes from API and should randomly pick one and send it as a prop to child component "Quote".
import React, {useState, useEffect} from 'react';
import Quote from './Quote.js';
function App() {
const[quotes, setQuotes]=useState();
const[randomQuote, setRandomQuote]=useState();
useEffect(()=>{
fetch("https://type.fit/api/quotes").then(
response=>response.json()).then(
data=>{setQuotes(data);
newRandomQuote()}
)},
[])
const newRandomQuote=()=>{
var randomQuote=quotes[Math.floor(Math.random() * 1643)]; // it's array of 1643 quotes
setRandomQuote(randomQuote);
}
return (
<div>
{quotes!=null&&<Quote quote={randomQuote}/>}
</div>
);
}
export default App;
But it seems like my newRandomQuote function didn't work, my randomQuote state is undefined, i don't understand it because it seems like i can access quotes State from outside of newRandomQuote but it is undefined from inside. If i add console.log(quotes) somewhere in component like this:
const newRandomQuote=()=>{
var randomQuote=quotes[Math.floor(Math.random() * 1643)];
setRandomQuote(randomQuote);
}
console.log(quotes);
return (
<div>
{quotes!=null&&<Quote quote={randomQuote}/>}
</div>
);
It works and show me array, so i don't get it.