How to prevent hydration issues when using the route query to change UI elements and fetch data?
So, let's say a /search page reads the current query in the URL, and uses it to change UI elements, for example, a search field or a filter component, then it uses this query to fetch the proper data and show the results.
How do we prevent Hydration issues in this case?
Do we have to isolate elements with
<client-only>
?
Or just make the whole route SSR: false?
Does generally, very dynamic pages always go for SSR: false?
Every time I change the UI based on content from the client (like, localStorage), I ran into this kind of issue.
I would like a bit more nuance on this, because it seems like the fix is always too harsh.
(If possible, share videos talking about it, or more details. Thanks!)5 Replies
what you described can be done on the server already (the "re-arranging") so no hydration issues should occur
doing that based on localstorage is a trickier situation
Maybe I'm missing something on how to properly build this.
So, the order of operations is just as I described:
1. Get the URL query object using a computed on route.query.
2. Populating the state used by UI elements with the data from the route query (in which the user will interact with, to change the search parameters).
3. Converting the route query object into an object that will be used to call the API to fetch the data.
So, Nuxt gives me hydration errors related to those UI elements that got changed on step 2.
I created a composable to keep the logic for these object conversions.
The page has a watcher that listens to route.query (with immediate: true), and populates the state (used by UI elements) with data from route.query.
What I observed is that the page is initially rendered with UI elements' default values, and in a second, changed to the current query.
can you provide a simple reproduction?
Sure, I'll get back to you soon
The real thing is a bit more complicated, but here it is: https://stackblitz.com/edit/nuxt-starter-fwapu3?file=components%2FMyHeader.vue
I found this issue, not sure if it is related
https://github.com/nuxt/nuxt.com/issues/1455
(🤔 I'll save this here as reference for later)
https://github.com/nuxt/nuxt.com/blob/main/composables/useShowcase.ts
that's more related to prerendering as you cant consider query params when you prerender pages