Next.js Discord

Discord Forum

How to show loading spinner during data fetching from page? (app dir)

Unanswered
Britannia Petite posted this in #help-forum
Open in Discord
Avatar
Britannia PetiteOP
I have few pages that fetch a lot of data. Instead having user to see the blank page, I'd like to show the spinner and then load the data. How that can be done? My pages are server components. I'd prefer fetch data from server action, not from /api folder. One idea I had is to have extra page which shows the spinner and performs client side redirect to another, but it feels a bit like dirty hack.

9 Replies

Avatar
@Britannia Petite I have few pages that fetch a lot of data. Instead having user to see the blank page, I'd like to show the spinner and then load the data. How that can be done? My pages are server components. I'd prefer fetch data from server action, not from /api folder. One idea I had is to have extra page which shows the spinner and performs client side redirect to another, but it feels a bit like dirty hack.
Avatar
you can add a loading.tsx to your path. This will wrap your page.tsx with a suspense boundary and will be then visible why you fetch data inside your page.tsx.

You loading.tsx can for example look like this:
export default function Loading() {
  // Or a custom loading skeleton component
  return <p>Loading...</p>
}
Avatar
Britannia PetiteOP
Yes I have that but when page.tsx is visited directly, it is blank till data loads
Avatar
@Britannia Petite Yes I have that but when page.tsx is visited directly, it is blank till data loads
Avatar
can you create a repro of that? For example via github or [codesandbox](https://codesandbox.io/)?
Avatar
Britannia PetiteOP
I just did but it works hmmm
Not in my codebase though, heh 😅
Avatar
hmmmm 🤔
what are you doing wrong? Maybe show your file structure
Avatar
Britannia PetiteOP
Nothing fancy really. I think I need to figure it on my own...
Image
Avatar
@Britannia Petite Nothing fancy really. I think I need to figure it on my own...
Avatar
hmm, that looks good to me. If you can provide a repro of the issue we can help you further 🙂
Avatar
Britannia PetiteOP
Thanks really appreciate it! Will play more later