nuxt
nuxt copied to clipboard
docs: recommend `$fetch` on top-level `<script setup>`
It is confusing why data is fetched twice when using $fetch on the client side without wrapping it with useAsyncData. It is explained here clearly. This PR updates docs to add clarification.
🔗 Linked issue
#18731
❓ Type of change
- [x] 📖 Documentation (updates to the documentation or readme)
- [ ] 🐞 Bug fix (a non-breaking change that fixes an issue)
- [ ] 👌 Enhancement (improving an existing functionality like performance)
- [ ] ✨ New feature (a non-breaking change that adds functionality)
- [ ] ⚠️ Breaking change (fix or feature that would cause existing functionality to change)
📚 Description
Complements PR #19356. It is confusing why $fetch fetches data twice when used on the client side with SSR. This PR adds details about this behavior.
📝 Checklist
- [x] I have linked an issue or discussion.
- [x] I have updated the documentation accordingly.
Open in CodeSandbox Web Editor | VS Code | VS Code Insiders
Much better, shall we move this into the best-practices section?
We should recommend everyone to not use $fetch in any .vue file if not wrapped with useAsyncData (or using useFetch) to avoid this double data fetching.
We should recommend everyone to not use
$fetchin any.vuefile if not wrapped withuseAsyncData(or usinguseFetch) to avoid this double data fetching.
Yes, that would be much better.
We should recommend everyone to not use
$fetchin any.vuefile if not wrapped withuseAsyncData(or usinguseFetch) to avoid this double data fetching.
Well, there are a few exceptions, e.g. when $fetch is in a function to, let's say send a form.
Indeed, so I guess it's top-level await inside a server-rendered component?
I think @manniL is suggesting something like:
<script setup>
async function submitForm() {
const data = /* */
await $fetch('/api/form', { body: data })
}
</script>
Indeed, so I guess it's top-level await inside a server-rendered component?
I think mainly top-level $fetch is relevant for this error, yes.