Reputation: 1518
Here I am having 4 components, where I am rendering all these four components in App.js. These four components individually hitting different APIs. So one component may render faster and others may render slower. What I am trying to achieve here is I need to show a loading indicator, till all components are rendered. I tried that using React Lazy loading and Suspense but no luck. Please help me with this. Here I am sharing the code of what I have done. Thanks in advance.
code:
import React, { Suspense, lazy } from "react";
import Navbar from "../layout/Navbar";
import Loader from "../layout/Preloader";
const Bar = lazy(() => import("./bar"));
const VariablePie = lazy(() => import("./variablePie"));
const Pie = lazy(() => import("./pie"));
const CombineChart = lazy(() => import("./combineChart"));
const Dashboard = () => (
<div>
<Navbar />
<Suspense fallback={<Loader/>}>
<main>
<div className="row" style={{ backgroundColor: "#eee" }}>
<div className="col s12 m6 l6" style={{ margin: "10px 0px" }}>
<Bar />
</div>
<div className="col s12 m6 l6" style={{ margin: "10px 0px" }}>
<VariablePie />
</div>
<div className="col s12 m6 l6" style={{ margin: "10px 0px" }}>
<Pie />
</div>
<div className="col s12 m6 l6" style={{ margin: "10px 0px" }}>
<CombineChart />
</div>
</div>
</main>
</Suspense>
</div>
);
export default Dashboard;
Upvotes: 0
Views: 3039
Reputation: 1938
You want to show loader till all components are rendered then you can have a counter variable in parent component (Dashboard in your case) and update its value when each component fetches the data and is ready to be rendered, in the parent check if the counter equals the no of loaded components needed then render all of them else keep rendering loader.
This approach has pitfalls, what if any of the API failed and the data was not loaded for that particular component, then, in that case, none of the components will be shown on screen. Make sure you handle such cases as well.
Upvotes: 1