Next.js Discord

Discord Forum

How to load data with Server Actions asynchronously

Answered
Almond stone wasp posted this in #help-forum
Open in Discord
Almond stone waspOP
I just started playing with server actions, and I made the following code:
async function getPosts() {
  "use server";

  await new Promise(r => setTimeout(r, 5000));

  return ["hello", "hey there", "wassup"];
}

I purposefully added a 5 second sleep just to simulate a worse case scenario for the dummy data loading
Here is how I am fetching the data in the component:
export default async function Home() {
  const posts = await getPosts();

  return (
        <div className="px-8 pb-20">
          {posts.map((post, index) => <h1 key={index}>{post}</h1>)}
        </div>
  );
}

Because of the await getPosts();, the server takes a really long time to initially send an HTML payload, which leaves the client's browser waiting for 5 seconds. I would rather have it send a dummy HTML (like a skeleton), and then fill the page with the loaded data. How can I do that? Should I just use api/ instead?
Answered by averydelusionalperson
U can use suspense or loading file.

Both are same, but the loading file wraps the entire component file, using Suspense you can wrap different components separately.

https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming
View full answer

4 Replies

U can use suspense or loading file.

Both are same, but the loading file wraps the entire component file, using Suspense you can wrap different components separately.

https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming
Answer
Almond stone waspOP
I will give it a try and report back