Home > OS >  Nuxt3 useFetch sends request only once
Nuxt3 useFetch sends request only once

Time:05-22

<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 >
      <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

CodePudding user response:

useFetch() sets up the fetch hook. It's not meant to be called multiple times. It needs to be at the top-level of <script setup> (not within a function) so that the hook can be properly installed for the component.

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

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

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

demo

CodePudding user response:

Thanks! Solved by adding param initialCache: false

useFetch('https://reqres.in/api/users?page=2?delay=1', { initialCache: false })
  • Related