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