nuxt icon indicating copy to clipboard operation
nuxt copied to clipboard

docs: recommend `$fetch` on top-level `<script setup>`

Open ozum opened this issue 2 years ago • 7 comments

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.

ozum avatar Mar 01 '23 05:03 ozum

CodeSandbox logoCodeSandbox logo  Open in CodeSandbox Web Editor | VS Code | VS Code Insiders

codesandbox[bot] avatar Mar 01 '23 05:03 codesandbox[bot]

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.

atinux avatar Mar 02 '23 10:03 atinux

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.

Yes, that would be much better.

ozum avatar Mar 02 '23 10:03 ozum

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.

Well, there are a few exceptions, e.g. when $fetch is in a function to, let's say send a form.

TheAlexLichter avatar Mar 02 '23 12:03 TheAlexLichter

Indeed, so I guess it's top-level await inside a server-rendered component?

atinux avatar Mar 02 '23 14:03 atinux

I think @manniL is suggesting something like:

<script setup>
async function submitForm() {
  const data = /* */
  await $fetch('/api/form', { body: data })
}
</script>

danielroe avatar Mar 02 '23 16:03 danielroe

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.

TheAlexLichter avatar Mar 02 '23 16:03 TheAlexLichter