Home > other >  Nuxt 3: useAsyncData with $fetch work only one time
Nuxt 3: useAsyncData with $fetch work only one time

Time:09-08

Hello everyone I'm using nuxt 3 for a project and I want to make a request to a typescript file in /server/api/ directory. But when I do in my file app.vue:

<script setup lang="ts">
const createPerson = async () => {
    console.log('create person')
    const data = await useAsyncData('createPerson', () => $fetch('/api/file', {
        method: 'POST',
        headers: useRequestHeaders(['cookie']),
        body: JSON.stringify({
            lastname: fields.value.lastname,
            firstname: fields.value.firstname,
            age: fields.value.age,
            x: fields.value.x,
            y: fields.value.y,
            bio: fields.value.bio
        })
    }))
    console.log(data)
}
</script>

and when I call this function createPerson from:

<button @click="createPerson">Apply</button>

my app fetch '/api/file' only one time and not re-fetching. If I use refresh function gived with useAsyncData, the first time I click on button I have two fetch and after one fetch.

CodePudding user response:

I'm not sure your issue but it seems your problem is about how you call your methods if you want to your method is been call everytime open page you should use 'mounted' also check this https://nuxtjs.org/docs/features/data-fetching/

CodePudding user response:

HOLLY JESUS !!! That's simple just set initialCache to false in useAsyncData parameters like this:

<script setup lang="ts">
const createPerson = async () => {
    console.log('create person')
    const data = await useAsyncData('createPerson', () => $fetch('/api/file', {
        method: 'POST',
        headers: useRequestHeaders(['cookie']),
        body: JSON.stringify({
            lastname: fields.value.lastname,
            firstname: fields.value.firstname,
            age: fields.value.age,
            x: fields.value.x,
            y: fields.value.y,
            bio: fields.value.bio
        })
    }), { initialCache: false })
    console.log(data)
}
</script>
  • Related