How to Use useFetch with '<script setup>' in Nuxt3 to Fetch Data from an API
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
I have researched the basic way of using <script setup>
and useFetch in Nuxt3 to fetch data from an API, and here is a summary.
Conclusion
<template>
<div>
<button @click="test">{{ data.weapons }}</button>
</div>
</template>
<script setup>
const config = useRuntimeConfig();
// config.baseUrl = http://127.0.0.1:8000
const { data } = await useFetch(`${config.baseUrl}/api/posts`);
const test = () => {
console.log(data.value.posts);
};
</script>
This seems to be the basic structure.
const { data } = await useFetch(`${config.baseUrl}/api/posts`)
Referencing data Requires value
When trying to reference the fetched data
inside:
<script setup></script>
data.value
is required.
<script setup>
const config = useRuntimeConfig();
// config.baseUrl = http://127.0.0.1:8000
const { data } = await useFetch(`${config.baseUrl}/api/posts`);
const test = () => {
console.log(data.value.posts);
};
</script>
useFetch or useAsyncData?
After reading various articles, my impression is that useFetch should suffice for most cases.
Therefore, in this article, I am using useFetch and think it is a good starting point. However, if you want more details, I recommend checking out other articles.
Why I Prefer useAsyncData Over useFetch in Nuxt3
Personally, I am accustomed to axios, and I think it is fine to use axios if you prefer.
Especially when using Laravel Sanctum for backend authentication, axios makes cookie authentication easier to manage.
Conclusion
That’s all for the basic structure of data fetching in Nuxt3.
I hope this helps someone.