0

I'm using a React.lazy along with Suspense to set a loading.

const LazyComponent = React.lazy(() => {
  const x = new Promise((resolve) => {
    setTimeout(() => {
      return resolve(import("../Components/ListContainer"));
    }, 3000);
  });
  return x;
});

function Home() {
  return (
    <> 
      <Suspense fallback={<Loading />}>
        <LazyComponent />
      </Suspense> 
    </>
  );
}

In my code, I set the timeout to 3000, but my objective is to make it loading until it completely fetched all the data and then renders all of the data at once.

Is there a way to achieve that? Or is there a better way to set a loading?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
itsMe
  • 133
  • 12
  • AFAIK Suspense should already handle that as long as the child has a React.lazy wrapped into it. – I am L Jun 07 '21 at 04:08
  • edited my post, the problem I'm facing is it will render and set the loading off and then render it one by one, but I expect it to render the data at once after the loading off. – itsMe Jun 07 '21 at 05:01
  • _"...make it loading until it completely fetched all the data..."_ in order for this to be possible the data fetching itself needs to have suspense integration. – Patrick Roberts Jun 07 '21 at 05:12

1 Answers1

0

You need to handle loading dynamically rather then give fix value of setTimeout.

> Here are steps you do it:

1- Create 3 actions for each network call: Like getDataPending, getDataSuccess, GetDataError

2- In getDataPending action put loading=false

3- In getDataSuccess action put loading=true and set Error=false

4- In getDataSuccess action put loading=true and set Error=true

5- Now call getDataPending right before network call

6- Call success action in getting response and Error action case of failure

This will help you to implement loading dynamically

Happy Coading

Muhammad Jaan
  • 291
  • 3
  • 10