I am working on React app which fetches large data (Thousands of records) and then render it. Until api is fetching data, UI keep blocked and does not display anything. I am creating chunks in size of 10 for fetching api using Promise.allSettled and combining them all.
useEffect(() => {
fetchBatchedData()
},[])
fetchBatchedData
is an async function and sets data in redux store only, I don`t need that data in UI at loading time. Until I get all the data, UI display nothing. How can I fetch data in background without blocking component rendering?
CodePudding user response:
You could use a useState like this:
const [data, setData] = useState();
useEffect(() => {
const loadData = () => {
const tempData = fetchBatchedData();
setData(tempData)
}
},[])
if(!data){
return(
<h1>Loading...</h1>
)
} else {
return(
<h1>Got the data!</h1>
)
}
CodePudding user response:
Maybe we can defer rendering the data? There is something called requestIdleCallback
here.
Something like this maybe?
import { useState, useEffect } from 'react';
function RenderDeferred({ children, timeout }) {
const [render, setRender] = useState(false);
useEffect(() => {
if (render) setRender(false);
const id = requestIdleCallback(() => setRender(true), { timeout: idleTimeout });
return () => cancelIdleCallback(id);
}, [idleTimeout]);
if (!render) return null;
return children;
}
And then use it like this:
<RenderDeferred timeout={3000}>
<YourComponent />
</RenderDeferred>