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->

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay