0

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;
SDK
  • 1,356
  • 3
  • 19
  • 44
  • Are the component bundles loading/fetching at different rates over the network, or once fetched/loaded they then make asynchronous calls to fetch and load data upon being mounted and some get this done more quickly? Are you using any global state management, like redux? – Drew Reese Mar 21 '20 at 06:03
  • It should work, `` component will be shown untill all components are loaded. React lazy will not control the api calls that individual components are making. – Gulam Hussain Mar 21 '20 at 06:04
  • https://reactjs.org/docs/concurrent-mode-suspense.html – ksav Mar 21 '20 at 06:06

1 Answers1

1

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.

Raj Saraogi
  • 1,780
  • 1
  • 13
  • 21