Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt3 useFetch sends request only once

<script setup lang="ts">

const loadPost = () => {
  console.log('load')
  const { data, pending, error, refresh } = useFetch(
    'https://jsonplaceholder.typicode.com/posts',
    {
      method: 'POST',
      body: {
        title: 'foo',
        body: 'bar',
        userId: 1,
      },
      headers: {
        'Content-type': 'application/json; charset=UTF-8',
      },
    })
  console.log(data)
}
</script>

<template>
  <div class="max-w-xs space-y-4 mx-auto mt-4">
      <button @click.prevent="loadPost">Load post</button>
  </div>
</template>

enter image description here

enter image description here

After clicking on the load button, I see every time the request is processed through the console log, but I do not see a new request in the network chrome devtools, I need to receive a response from the server every time, how can I do this?

Note: If I use a regular fetch(), then the request is sent every time, as it should be

my nuxt version - 3.0.0-rc.1

like image 627
Dmitry Cosmos Avatar asked Oct 12 '25 11:10

Dmitry Cosmos


2 Answers

Thanks! Solved by adding param initialCache: false

useFetch('https://reqres.in/api/users?page=2?delay=1', { initialCache: false })
like image 174
Dmitry Cosmos Avatar answered Oct 15 '25 11:10

Dmitry Cosmos


If you want to re-fetch the data, use the refresh() method returned from useFetch():

<script setup lang="ts">
const { data, pending, error, refresh } = await useFetch('https://reqres.in/api/users?page=2?delay=1')

const loadPost = () => {
  refresh()
}
</script>

demo

like image 30
tony19 Avatar answered Oct 15 '25 10:10

tony19