I have a page where an api loads slowly and only two buttons are displayed in my page for some seconds so I have decided to add loader in that page I have tried the below code but the loader is loaded not the page table
import Loader from '../Loader/Loader';
const FileTable = () => {
const [isVisible, setIsVisible] = useState(true);
const handleLoading = () => {
setIsVisible(false);
}
useEffect(() => {
window.addEventListener("load",handleLoading);
return () => window.removeEventListener("load",handleLoading)
},[])
return !isVisible ? (
<div>
My component
</div>
):(
<div>
<h1>Loading...</h1>
</div>
)
}
export default FileTable;
I even tried the below code
const [isVisible, setIsVisible] = useState(false);
and then
if(!isVisible){
return <>Loading</>
}
return(
<>
My Component
</>
)
I have tried both the ways but the loader is not working. The buttons should also hide when the page loads only the loader should be displayed until the api loads How do I fix it?
A simple and straightforward scenario would be:
A sample code would be as the following:
const MyComponent = () => {
const [loading, setLoading] = useState(true);
const [apiData, setApiData] = useState([]); // or whatever
const handleClose = () => {
setLoading(false)
}
useEffect(() => {
// Init API call here
// then( ..... setApiData()) // Do whatever with API response to set component apiData
// finally (() => setLoading(false))
}, []) // empty dependency array is equivalent to componentDidMount
if(loading) {
return <Loader />
}
return <Component data={apiData} />
}
It is also a good practice to handle eventual API call failures