useFetch()

Hello friends, I'm curious about how to use status.value correctly with useFetch().
No description
2 Replies
kapa.ai
kapa.ai3w ago
Hi @ლაზარე ჩხარტიშვილი. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Certainly! I'd be happy to explain how to use status.value correctly with useFetch() in Nuxt 3. The useFetch() composable in Nuxt 3 returns an object that includes a status property, which is a reactive ref indicating the current state of the data fetching process. Here's how you can use it: 1. The status value can be one of four states: - 'idle': When the fetch hasn't started - 'pending': When a fetch has started but not yet completed - 'error': When the fetch fails - 'success': When the fetch is completed successfully 2. You can access the status using status.value in your script, or just status in your template. Here's an example of how to use it:
<script setup>
const { data, status } = useFetch('/api/posts')
</script>

<template>
<div v-if="status === 'pending'">
Loading...
</div>
<div v-else-if="status === 'error'">
An error occurred
</div>
<div v-else-if="status === 'success'">
<div v-for="post in data" :key="post.id">
{{ post.title }}
</div>
</div>
</template>
<script setup>
const { data, status } = useFetch('/api/posts')
</script>

<template>
<div v-if="status === 'pending'">
Loading...
</div>
<div v-else-if="status === 'error'">
An error occurred
</div>
<div v-else-if="status === 'success'">
<div v-for="post in data" :key="post.id">
{{ post.title }}
</div>
</div>
</template>
In this example, we're using the status to show different content based on the current state of the fetch operation. You can also use status.value in your script to perform different actions based on the fetch status:
<script setup>
const { data, status } = useFetch('/api/posts')

watch(status, (newStatus) => {
if (newStatus === 'success') {
console.log('Data fetched successfully!')
}
})
</script>
<script setup>
const { data, status } = useFetch('/api/posts')

watch(status, (newStatus) => {
if (newStatus === 'success') {
console.log('Data fetched successfully!')
}
})
</script>
Remember that status is a ref, so you need to use .value when accessing it in the script section, but not in the template. For more detailed information, you can refer to the Nuxt 3 documentation on useFetch. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3w ago
<@941371689181282327> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?