Nuxt3 useFetch not refreshing on slug change

1.6k Views Asked by At

I am trying to use nuxt3s useFetch feature to fetch the pages content. Whenever the slug changes I want to refetch/refresh.

The docs (https://nuxt.com/docs/getting-started/data-fetching) tell me that:

  1. the URL is auto-watched, so a refresh should always happen if my URL changes
  2. that I could use the watch property within useFetch to refresh

Both does not work. I even tried to watch the slug with a watcher and trigger a refresh. No success either. Somehow the whole await useFetch() is just never called anymore...

Here is my code:

<script setup>

const runTimeConfig = useRuntimeConfig()


// Tried to use this, but I don't really understand what that key is for:
// definePageMeta({
//   key: (route) => route.params.slug,
// })

const route = useRoute()
const slug = computed(() => route.params.slug)

const endpoint = `${runTimeConfig.public.API_URL}/wp/v2/pages?slug=${slug.value}`
console.log('endpoint: ', endpoint)

const {
  data: page,
  pending,
  error,
  refresh,
} = await useFetch(endpoint, {
  key: `key-${slug.value}`,
  initialCache: false,
})

console.log('page: ', toRaw(page.value))

Now if I change the slug, I can see that the endpoint log is appearing with the correct URL. But if I log the page, after navigation it logs:page: null...

Also that value is not updated later (first I thought the async await stuff is not working properly).

1

There are 1 best solutions below

5
On

useFetch refetch dynamic params useRoute().params

~/pages/test-params/[id].vue

<script lang="ts" setup>
const { data } = await useFetch('/api/param', {
  params: useRoute().params,
});
</script>
<template>
  <div>
    <h1>Dynamic Param is: {{ data }}</h1>
    <div v-for="param in 10" :key="param">
      <NuxtLink :to="`/test-params/${param}`">Navigate To {{ param }}</NuxtLink>
    </div>
  </div>
</template>
<style scoped lang="css"></style>
API route ~/server/api/params.get.ts

export default defineEventHandler((event) => {
  const { id } = getQuery(event);
  return id;
});

useFetch refetch dynamic query useRoute().query

<script lang="ts" setup>
//const querySlug = computed(() => useRoute().query.slug ?? 1)  - If you want to add a default;
const querySlug = computed(() => useRoute().query.slug)
const { data: slug } = await useFetch('/api/slug', {
  query: { slug: querySlug },
})
</script>
<template>
  <div>
    <h1>Query</h1>
    <h3>Selected Query: {{ slug }}</h3>
    <div
      v-for="slug in 10"
      :key="slug"
    >
      <NuxtLink :to="`/?slug=${slug}`">Query to {{ slug }}</NuxtLink>
    </div>

    <div style="margin-top: 40px;">
      <NuxtLink to="/">Remove query</NuxtLink>
    </div>
  </div>
</template>
<style scoped lang="css"></style>

API route example ~/server/api/slug.get.ts

export default defineEventHandler((event) => {
  const { slug } = getQuery(event);
  return slug;
});