DEV Community

Prince Patel
Prince Patel

Posted on

1

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)

Billboard image

Use Playwright to test. Use Playwright to monitor.

Join Vercel, CrowdStrike, and thousands of other teams that run end-to-end monitors on Checkly's programmable monitoring platform.

Get started now!

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay