SWR + Suspense for client-side data fetching #53049
Unanswered
dbk91
asked this question in
App Router
Replies: 1 comment 1 reply
-
Hello! |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I know that data-fetching on the server using server components is one of the major features with the App Router, but I wanted to gain some insight and clarity on client-side data fetching, specifically using Suspense to leverage the
error.js
andloading.js
special files. I'll use SWR in my example since that's what I'm familiar with and it's also what the Next docs recommend.While there are straight-forward and documented ways to use SWR without Suspense, there doesn't seem to be much communication in the way of using Suspense with libraries like SWR. I've done quite a bit of testing around this, and it appears that this is the most reliable solution:
The reason
useSearchParams
is invoked is to opt the client component out of static-rendering. If this is invoked prior touseSWR
, the production build of this will work with no issues and display a loading state provided the following files exist.Like I mentioned before, this achieves the traditional SPA approach to data fetching while improving DX using the special files for loading and error states. The only drawback to this solution is that SWR throws an error about requiring
fallbackData
during SSR when this code is run innext dev
. However, if you were to circumvent this error by providingfallbackData
, you lose the loading state since the initial data is placed in SWR on the server-side and hydrated on the client. Initially I thought SWR would have to change something on their end to accommodate this use-case, but then it occurred to me that it's more likely the error is thrown since Next is not opting the component out of static-rendering for dev.My questions from all of this are:
next dev
despite the fact that they useuseSearchParams
?use
, yet?Aside from that, thanks to the Next team for improving upon an already great framework. We've been early adopters of App Router and aside from a few minor snags, it's been a pure joy to use. 👍
Beta Was this translation helpful? Give feedback.
All reactions