DEV Community

Prince Patel
Prince Patel

Posted on

How to display loading during api call in React JS

npx create-react-app your-app-name
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Make state of loading and data in your page

App.js

const [isLoading,setIsLoading] = useState(false);
const [error,setError] = useState();
const [data,setData] = useState({});
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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);
  })    
}
Enter fullscreen mode Exit fullscreen mode

Output

Loader

Image description

After fetching data

Image description

For source code - github/princepatel157/loader

Also visit my blog - visit->

Top comments (0)