#Hydration warning with client-only fetching
1 messages · Page 1 of 1 (latest)
To address the hydration warning when using useFetch with { server: false } and handling a pending state, you can use the useLazyFetch composable and wrap your content in a <client-only> component. Here's how you can modify your code to solve this issue:
<script setup>
const { pending, data: posts } = useLazyFetch('/api/posts')
</script>
<template>
<client-only>
<div v-if="pending">Loading...</div>
<div v-else>
<div v-for="post in posts">
<!-- do something with post -->
</div>
</div>
</client-only>
</template>
This approach solves the hydration mismatch problem by:
-
Using
useLazyFetchinstead ofuseFetch.useLazyFetchis equivalent to usinguseFetchwith thelazy: trueoption, which means it won't block navigation and will start fetching on the client-side. -
Wrapping the content in a
<client-only>component, which ensures that the content is only rendered on the client-side, avoiding hydration mismatches.
The reason for the hydration warning is that when you use { server: false }, the data fetching only occurs on the client-side. This can lead to a mismatch between the server-rendered HTML (which doesn't have the data) and the client-side rendered content (which does have the data after fetching).
By using useLazyFetch and <client-only>, you ensure that the fetching and rendering happen consistently on the client-side, avoiding hydration mismatches.
For more information on this topic, you can refer to the following Nuxt documentation: