Next.js Discord

Discord Forum

Loading UI when search params change

Unanswered
Thrianta posted this in #help-forum
Open in Discord
ThriantaOP
I have an app that uses pagination with RSC. The query parameters are passed from Next.js straight to an API endpoint which returns the result set.

I can't seem to find a way to show a loading UI when paginating. I have the same issue for things like filters which appear on the page. When clicking a pagination button, I programmatically update the search params (because filters need to stay in place) and use router.replace to update the URL. This works, but the new UI only shows after 1 second or so, because the API isn't fast.

What is the best way to get a loading UI here? Suggestions online seem to only help when fetching data directly on the client, which I don't want.

8 Replies

Siberian Flycatcher
Hi 👋

You can re-trigger loading fallback when searchParams change by providing a key prop to Suspense with the changing search param.

function MyComponent({searchParams}) {
  return (
    <Suspense
      key={searchParams.prop}
      fallback={// loading ui}>
      <ServerComponent />
    </Suspense>
  )
}
ThriantaOP
@Siberian Flycatcher Thanks Alex! Any way I can build a loading UI that isn't the fallback? For example, if I have a button that changes the search params, I'd love to just show a small spinner inside the button. Something like const isLoading = useNavigationInProgress() ?
Siberian Flycatcher
Yep, you can do this by extracting your button into a separate client component and using useTransition with router.push to show the loading indicator.

https://twitter.com/asidorenko_/status/1700102583208034746
ThriantaOP
Ohhh that looks exactly like what I want! That's great! Thanks 🙂
ThriantaOP
One more follow up if I may: This makes it work nicely with router.replace/push calls. How can I make it work for form submissions?
Siberian Flycatcher
You'll need to use useFormStatus for this one.

Here is an example:
https://twitter.com/asidorenko_/status/1701933750437740885
ThriantaOP
Thanks so much! Hard to believe I couldn't find this online... Super helpful 🙂