Watching Reactive Sources

Re-Fetch When a Ref Changes

Watching Reactive Sources

Pass a function URL or use the watch option to make useFetch automatically re-run when reactive inputs change.

4 min read Level 2/5 #nuxt#fetching#watch
What you'll learn
  • Use a function URL that depends on a reactive ref
  • Use the watch option to list explicit dependencies
  • Avoid infinite re-fetch loops

Most lists need to react to user input — pagination, filters, search. Nuxt makes the URL itself reactive.

Function URLs

<script setup lang="ts">
const id = ref(1)

const { data: user } = await useFetch(() => `/api/users/${id.value}`)
</script>

<template>
  <button @click="id++">Next user</button>
  <pre>{{ user }}</pre>
</template>

Every time id.value changes, the URL recomputes and useFetch re-runs.

The watch Option

When the URL stays the same but options change, use watch:

<script setup lang="ts">
const page = ref(1)
const tag = ref('js')

const { data } = await useFetch('/api/posts', {
  query: { page, tag },
  watch: [page, tag]
})
</script>

You can also pass watch: false to opt out of any auto-refetch.

Avoid Loops

A common trap: writing to the watched ref from inside the response handler.

// BAD — onSuccess mutates page, which triggers another fetch.
const { data } = await useFetch('/api/posts', {
  query: { page },
  watch: [page],
  onResponse({ response }) {
    page.value = response._data.nextPage // infinite loop
  }
}

Update the ref only in response to user events, not inside fetch callbacks.

Forwarding Headers and Cookies →