Nuxt 3: useAsyncData and $fetch only work once
P粉018548441
P粉018548441 2023-11-04 00:03:52
0
1
648

I'm using nuxt 3 in a project and I want to make a request to a typescript file in the /server/api/ directory. But when I do this in 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>

When I call this function createPerson:

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

My application only fetches "/api/file" once and does not re-fetch it. If I use the refresh function provided by useAsyncData, I have two fetch when the button is clicked for the first time and one fetch after that.

P粉018548441
P粉018548441

reply all(1)
P粉163465905

To answer your question, you need to add a key to use AsyncData to force a refresh on your request. The reason the refetching does not occur is that createPerson remains unchanged as the key, so no refetching is performed. So all you need to do is generate a random key using your favorite useAsyncData method

<script setup lang="ts">
    const createPerson = async () => {
        console.log('create person')
        const data = await useAsyncData(RANDOM_KEY, () => $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>

You can also choose to use the refresh function without worrying about the key. Check this documentation https://nuxt.com/docs/getting -started/data-fetching#refreshing-data

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