Why useFetch is not working on page change in nuxt3 on client side?
Asked Answered
E

3

8

I just started learning nuxtjs (have some experience in vue.js) and I stuck into the following problem:

I have a simple todo-[id].vue page. It should get an todo from the API and render on the page:

<script setup>
import Section from '~~/components/UI/containers/section.vue';
import ButtonLink from '~~/components/UI/buttons/button-link.vue';

const route = useRoute()
const todoId = parseInt(route.params.id)
const { data: todo } = await useFetch(`https://jsonplaceholder.typicode.com/todos/${todoId}`)
</script>

<template>
  <Section>
    <div class="mt-4 flex space-x-4">
      <ButtonLink :to="{name: 'todo-id', params: {id: todoId - 1}}" type="secondary" v-show="todoId !== 1">previous</ButtonLink>
      <ButtonLink :to="{name: 'todo-id', params: {id: todoId + 1}}">next</ButtonLink>
    </div>
    <div class="mt-6">
      <p class="text-lg" :class="[todo.completed ? 'text-green-600' : 'text-red-600']">{{ todo.title }} (#{{ todo.id }})</p>
    </div>
  </Section>
</template>

It works fine on the server side, but when I'm clicking on the next button it does not call the API to get next item, page's url is changing. What should I do to call the API on the client side? As I remember it works fine in vue.js

English answered 15/8, 2022 at 7:50 Comment(2)
What is button-link? Also, where is the code of your snippet located? In todo-[id].vue too? What do you see in your console/network tab?Toler
hey.. se my answer here: #73415650 . just use $fetch() instead of useFetch.Mciver
I
7

useFetch tries to cache the document for you and reuses the cache when you load the next page. To avoid that behavior you can pass a function instead of a string:

useFetch(() => `https://jsonplaceholder.typicode.com/todos/${todoId}`)

or provider your own key:

useFetch(`https://jsonplaceholder.typicode.com/todos/${todoId}`, { key: `todo:${todoId}` })

Docu: https://v3.nuxtjs.org/api/composables/use-fetch

Illinium answered 8/9, 2022 at 10:59 Comment(1)
I had the same issue as OP. This worked!Agree
C
3

From nuxt3's useFetch documentation:

watch: watch reactive sources to auto-refresh.

Also, I currently have to set key and initialCache: false to useFetch to make sure the fetch run every time enter page.

Ctenidium answered 8/10, 2022 at 15:28 Comment(1)
This does not work for me. Could you show an example of yours? I tried to generate a key with a timecode (so I get something new) and I have set initialCache to false. Also the refetch should anyway happen because the URL changes...Bisque
K
1

In my case, using Nuxt 3 i added:

server: false

useFetc:h Source Fetch data from an API endpoint with a SSR-friendly composable.

By default, useFetch fetches the data on the server.

https://nuxt.com/docs/api/composables/use-fetch

Kerwon answered 27/11, 2023 at 11:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.