Nuxtjs Async Data
In this tutorial, you'll learn about Nuxt.js Async Data Error Fix. We cover key concepts, practical examples, and best practices.
The Problem
[nuxt] [request error] Cannot read properties of undefined (reading 'data')
useAsyncData returns undefined when the fetch function throws an error.
Wrong
<script setup>
const { data } = useAsyncData('posts', () => {
return $fetch('/api/posts') // May throw
})
console.log(data.value) // May be undefined
</script>
If the API returns an error, data is undefined and the template may crash.
Right
<script setup>
const { data, pending, error, refresh } = useAsyncData('posts',
() => $fetch('/api/posts'),
{
transform: (response) => response ?? [],
default: () => [],
}
)
</script>
<template>
<div>
<div v-if="pending">Loading...</div>
<div v-else-if="error">Error: {{ error.message }}</div>
<ul v-else>
<li v-for="post in data" :key="post.id">{{ post.title }}</li>
</ul>
</div>
</template>
Expected output: loading state, error state, and data state are all handled gracefully.
Prevention
- Always destructure
pending,error, andrefreshfromuseAsyncData - Provide a
defaultvalue for initial render - Use
transformto normalize API responses
Common Mistakes with async data
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world NUXTJS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro