Next.js Discord

Discord Forum

Server Component Complex Data Fetching

Unanswered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
Let's imagine you have an endpoint on BE, which from the first call returns to you some partial data. And after the first call you need to re-fetch for missing and partially missing data. This endpoint also expects x amount of retrials. For such cases, we can write recursive data fetching fn, and until it is resolved - show some loading indication on UI. But loading can take quite a bit of time
So the goal is - to show ASAP already fetched data, which is ready to be rendered, and fetch the rest in the background.
To achieve this goal I use this flow:
1) Render server component, which fetches initial data.
2) This component returns client & server components
The client component will bring ready data to the client. All it does is save data to redux store on render. From the Redux store, we build our client app
The server component - the initial component, recursively called to fetch the rest of the data
3) Continue recursively rendering server component until all data will be fetched, or we'll reach the retrial limit

The question is - is there a more optimal way to achieve this goal? Maybe I am missing something? Is there any way to trigger additional data fetch from a client?
Maybe at some point server actions can be used for such purposes https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
Or somehow create async generator functional components for multiple returns)) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator

0 Replies