'How can I add loading spinner while fetching data on react app?

How to add loading spinner while fetching. I want to add loading spinner on fetch data on my react app.



Solution 1:[1]

you can use react Suspense and lazy for it. here below is a code example.

import { Suspense, lazy } from "react";

import Loading from "./loading";
const Loaded = lazy(() => import("./loaded"));

const App = () => {
  return (
    <Suspense fallback={<Loading />}>
      <Loaded />
    </Suspense>
  );
};

you can read mode about the suspense here suspense

here is sandbox Link sanbox

Solution 2:[2]

You need to have a loading state based on how you are fetching the data for example if you are fetching data using axios you need to set the loading to true in the beginning of your fetch function and set it to false on receiving data or on error.

const App = () => {
  const [loading, setLoading] = useState(false);

  const fetchFunction = () => {
    setLoading(true);
    .
    .
    .
    if (data || error) {
      setLoading(false);
    }
  };

  if (loading) return <Loading />;

  return <Data />;
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mohammad K.