Nuxt

nuxt/fetch-composable-in-handler

Call useFetch and useAsyncData only in setup, plugins or composables; in event handlers use $fetch.

moderatestaticfe-nuxt

Why

useFetch and useAsyncData register state with the current component and the page payload. Called from a click or submit handler, there is no setup context: each call creates new refs nobody watches, keys collide, results are cached when they should not be, and warnings about the missing Nuxt instance appear.

Fix

Use $fetch in event handlers (await $fetch('/api/orders', { method: 'POST', body })), then update your state or call refresh() of a useFetch declared in setup. Wrapping useFetch in your own use... composable is fine, as long as that composable is called from setup.

Examples

// bad
async function onSubmit() {
  const { data } = await useFetch('/api/orders', { method: 'POST', body: form })
}
// good
const { data: orders, refresh } = await useFetch('/api/orders')
async function onSubmit() {
  await $fetch('/api/orders', { method: 'POST', body: form })
  await refresh()
}

Sources

Facts

Id
nuxt/fetch-composable-in-handler
Severity
moderate
Check
static checked in the source by audit
Applies to
vue jsx
Only in projects with
nuxt
Taught by the skill
fe-nuxt Nuxt apps
Since version
0.1.0

Rule file on GitHub

Read it in the terminal

npx github:dawidolko/frontend-skills explain nuxt/fetch-composable-in-handler