npx create-react-app your-app-name
Create Loader component in components folder
Loader.js
import React from "react";
import "./Loader.css";
export default function Loader() {
return (
<div className="loader-container">
<div className="loader">
</div>
</div>
);
}
Loader.css
@keyframes load {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.loader-container{
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.loader {
width: 50px;
height: 50px;
border: 10px solid #f3f3f3;
border-top: 10px solid #0c2455;
border-radius: 50%;
animation: load 1.5s linear infinite;
}
Make state of loading and data in your page
App.js
const [isLoading,setIsLoading] = useState(false);
const [error,setError] = useState();
const [data,setData] = useState({});
Make condition according to loading value in returning data
<section className='data-container'>
<div className='data'>
{ isLoading? <Loader/> : error? error : data.fact }
</div>
<button onClick={fetchData}>Get Data</button>
</section>
Api call and change state of loading
const fetchData = () =>{
setIsLoading(true);
fetch('https://catfact.ninja/fact')
.then(function(res){
return res.json();
})
.then(function(res){
console.log(res);
setData(res);
setIsLoading(false);
})
.catch(()=>{
setError("Unable to fetch data...")
setIsLoading(false);
})
}
Output
Loader
After fetching data
For source code - github/princepatel157/loader
Also visit my blog - visit->
Top comments (0)