1

I fetch 5 API in difference Component.

I give both 5 API Timeout for 3000 milisecond, so how can i set loading screen for 5 component when the setTimeout are going and make the loading screen gone and return the data when setTimout is done.

The Code:

function App() {
  const [loading, setLoading] = useState(false)
  
 
  return ( 
  {loading ?  <> <Component1 setLoading={setLoading}/>
      <Component2/>
      <Component3/>
      <Component4/>
      </>  : <LoadingScreen/>
       }
  )
}

inside Component1 code:

function Component1({setLoading}) {
  const [data, setData] = useState([]);
const loadData = async() =>{
      const datas = await fetch(`theapi`);
      const value = await anime.json()
      if (datas.ok) {
        setTimeout(() => {
          return   setData(value.data);
        }, 3000);
        setLoading(false)
      }
  }

  useEffect(() =>{
    
      loadData();
  },[])
  return (
    <>
    {data}
    </>
  )
}

Btw all my Component using the same fetch method. Thanks for the Help

NewGuyHere
  • 15
  • 3

1 Answers1

0

You could achieve that changing a little bit the state. Instead of:

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

do:

const [areFetching, setAreFetching] = useState({
  component1: true,
  component2: true,
  component3: true,
  component4: true,
});

And inside each component:

setTimeout(() => {
  return   setData(value.data);
  }, 3000);
setAreFetching((fetching) => ({ ...fetching, componentNUMBER: false}));

So, in this way, in your App component add the following lines:

function App() {
  const [areFetching, setAreFetching] = useState({
    component1: false,
    component2: false,
    component3: false,
    component4: false,
  });
  const isFetched = Object.values(areFetching).every(fetched => fetched === false);

if (!isFetched) return (<LoadingScreen/>);

  return ( 
    <>
      <Component1 setLoading={setLoading}/>
      <Component2 setLoading={setLoading}/>
      <Component3 setLoading={setLoading}/>
      <Component4 setLoading={setLoading}/>
    </>
  )
}