So on my journey of learning react I've built this simple app , It renders a quote from an API and display it with every button click , I've run to issues when i tried to display the quote and I've used some vanilla JavaScript. Here's my code
function App() {
const [error , setError] = useState(null);
const [isLoaded ,setIsLoaded] = useState(false);
const [dataQuotes , setDataQuotes] = useState([]);
useEffect(() => {
fetch('https://type.fit/api/quotes')
.then(res => res.json())
.then(
(results) => {
setIsLoaded(true)
setDataQuotes(results)
},
(error) => {
setIsLoaded(true)
setError(error)
}
)
},[])
function getQuote(){
const Quotes = dataQuotes
const randomNumber = Math.floor(Math.random()*Quotes.length)
const finalData = Quotes[randomNumber]?.text
document.getElementById('content').innerHTML=`"${finalData}"`
}
if (error) {
return <div>Error :{error.message}</div>
} else if (!isLoaded) {
return <div>Loading...</div>
} else {
return (
<>
<div className='container'>
<h3 id='content'>{}</h3>
</div>
<button onClick={getQuote} className='btn'>Generate Quotes</button>
</>
);
}
}
Is there any modifications i can apply to make the code cleaner , because I feel like I can make it better and cleaner
CodePudding user response:
Most of it looks clean already. I have pointed out a few changes below.
function App() {
const [error , setError] = useState(null);
const [isLoaded ,setIsLoaded] = useState(false);
const [dataQuotes , setDataQuotes] = useState([]);
const ref = useRef();
useEffect(() => {
fetch('https://type.fit/api/quotes')
.then(res => res.json())
.then(
(results) => {
setIsLoaded(true)
setDataQuotes(results)
},
(error) => {
setIsLoaded(true)
setError(error)
}
)
},[])
function getQuote(){
const Quotes = dataQuotes
const randomNumber = Math.floor(Math.random()*Quotes.length)
const finalData = Quotes[randomNumber]?.text
//document.getElementById('content').innerHTML=`"${finalData}"`
ref.current.innerHTML = finalData
}
return (
<>
{error ?
<div>Error :{error.message}</div>
:
!isLoaded ?
<div>Loading...</div>
:
<>
<div className='container'>
<h3 id='content' ref={ref}>{}</h3>
</div>
<button onClick={getQuote} className='btn'>Generate Quotes</button>
</>
}
</>
);
}
}
CodePudding user response:
You have two times setIsLoaded(true)
: one in .then
and another in .error
.
You can use .finally(() => { setIsLoaded(true) }
.