How to add loading spinner while fetching. I want to add loading spinner on fetch data on my react app.
CodePudding user response:
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
CodePudding user response:
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 />;
};