Using useFetch to retain cached data in Nuxt3
P粉547420474
P粉547420474 2023-11-03 21:01:41
0
2
932

I encountered the following problem when using nuxt3.

  • Dynamic page[slug].vueLoad the initial slug data correctly
  • When I leave the page and come back, the new data does not load, instead the old data is still displayed.
  • If I refresh said page with old data it works fine.

This seems to happen because the api call for the new slug is never made.

My [slug.vue] The file looks like this:

<script setup lang="ts">
import { ref } from 'vue';
const route = useRoute();

const slug = ref(String(route.params.slug));
console.log(slug.value);
const apicall = `https://swapi.dev/api/people/${slug.value}`;
const { data: article } = await useFetch(
  `https://swapi.dev/api/people/${slug.value}`
);
</script>
<template>
  <div>
    <NuxtLink to="/">Back to Home</NuxtLink>
    <pre>
      {{ `https://swapi.dev/api/people/${slug}` }}
      {{ route.params.slug }}
      {{ article }}
    </pre>
  </div>
</template>

The entire setup can be seen on stackblitz: https://stackblitz.com/edit/nuxt-starter-mkgfrw?file=pages/[slug].vue,pages/index.vue

P粉547420474
P粉547420474

reply all(2)
P粉523625080

By default, useFetch, useLazyFetch, useAsyncData, and useLazyAsyncData all cache the initial response payload initially fetched in the current browser session, so no useless subsequent requests are made. (At least, I guess that's the idea behind it)

You can change the default behavior of each fetch composable by passing the option "initialCache" and setting it to "false".

See: https://v3.nuxtjs.org/api /composables/use-async-data#params

P粉464082061

Following the suggestions in the comments above and checking the documentation here: https://v3.nuxtjs.org/guide/features/data-fetching/#refreshing-dataI tried the following which worked Code

const { data: article, refresh } = await useFetch(
  `https://swapi.dev/api/people/${slug.value}`
);

watchEffect(() => {
  refresh();
});

Working example here: https://stackblitz.com/edit/nuxt-starter-mkgfrw?file=pages/[slug].vue,app.vue

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template