0

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?

1
  • Have you tried webworker for async fetch? Commented Oct 7, 2022 at 6:21

2 Answers 2

1

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>
  )
}

Sign up to request clarification or add additional context in comments.

1 Comment

No this is not the issue. Issue is render blocking not the displaying.
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.