1๐
โ
I think you are missing a lot about React fundamentals and you should go read the docs which have plenty of examples and patterns. What you want to do is make sure your component can handle a "loading" state. Async requests are not immediate and take time, what is your component going to look like while you wait for the request to complete ?
I am using a state variable to track the completion of the request. I would recommend looking up how useEffect works as well to better understand this snippet.
import AvgVisitDuration from './component/AvgVisitDuration';
import Devices from './component/Devices';
import About from './component/About';
import { useEffect, useState } from 'react';
function App() {
const [devices, setDevices] = useState([])
const [loadingDevices, setLoadingDevices] = useState(false)
useEffect(() => {
async function getStats() {
setLoadingDevices(true)
try {
const response = await fetch('http://192.168.1.4:8080/api');
const data = response.json();
const transformData = ... // do whatever you need to do to extract the data you need from the async call
setDevices(transformData)
setLoadingDevices(false)
} catch(e) {
setLoadingDevices(false)
}
}
getStats();
}, [setStats, setLoadingDevices])
return (
<div className='container'>
<About />
<AvgVisitDuration />
{loadingDevices ? <div>loading ...</div> : <Devices Data={devices} />}
</div>
);
}
export default App;
Source:stackexchange.com