Data Fetching & State
Relevant source files
The following files were used as context for generating this wiki page:
The Data Fetching and State management system in Nuxt provides a unified interface for handling asynchronous data operations and global reactive state across server and client environments. It is designed to optimize performance by preventing duplicate data fetching during hydration and enabling efficient state sharing between components.
The system relies on primary composables like useAsyncData, useFetch, and useState. These tools leverage the Nuxt internal payload system to serialize data on the server and "revivify" it on the client, ensuring a seamless transition during hydration without redundant network requests.
Sources: packages/nuxt/src/app/composables/asyncData.ts, packages/nuxt/src/app/composables/state.ts
Asynchronous Data Fetching
Nuxt manages asynchronous operations through useAsyncData and its wrapper, useFetch. These composables handle the lifecycle of a request, providing reactive states for data, loading status, and errors.
useAsyncData Architecture
useAsyncData is the core primitive for executing asynchronous logic. It uses a unique key to track requests and cache results in the Nuxt instance. This ensures that if a key is already present in the payload during hydration, the fetcher function is skipped.
The diagram above illustrates the logical flow of useAsyncData, highlighting the cache-first approach used during hydration.
Sources: packages/nuxt/src/app/composables/asyncData.ts:88-120, test/nuxt/use-async-data.test.ts:983-990
key Features and Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Unique identifier to deduplicate and cache requests. |
handler | () => Promise | Asynchronous function that returns data. |
lazy | boolean | If true, resolves after the component is mounted (client-side only). |
immediate | boolean | Whether to execute the handler immediately. Defaults to true. |
watch | Array<WatchSource> | List of reactive sources to trigger a re-fetch on change. |
dedupe | 'cancel' | 'defer' | Strategy for handling concurrent requests with the same key. |
Sources: packages/nuxt/src/app/composables/asyncData.ts:18-50
HTTP Fetching with useFetch
useFetch is a high-level wrapper around useAsyncData specifically designed for HTTP requests. It internally uses $fetch (powered by ofetch) and automatically generates a cache key based on the URL and fetch options.
request Interception and Deduplication
useFetch intercepts request parameters to ensure they are reactive. It supports automatic key generation based on the provided URL, which prevents developers from having to manually manage keys for standard API calls.
This sequence diagram shows how useFetch abstracts the key generation and data fetching process.
Sources: packages/nuxt/src/app/composables/fetch.ts:114-140, test/basic.test.ts:742-747
State Management
useState is the primary tool for creating shared, reactive state that is preserved between the server and the client. Unlike Vue's ref, useState ensures that the state initialized on the server is automatically hydrated on the client.
Payload Serialization
When useState is called on the server, the value is stored in nuxtApp.payload.state. This object is then serialized into the HTML sent to the client. Upon initialization in the browser, Nuxt populates the internal state from this payload.
This diagram demonstrates the lifecycle of a state variable from server initialization to client restoration.
Sources: packages/nuxt/src/app/composables/state.ts:25-45, test/basic.test.ts:45-50
state Composable API
| Function | Signature | Description |
|---|---|---|
useState<T> | (key: string, init?: () => T) => Ref<T> | Creates or retrieves a reactive state associated with a key. |
clearNuxtState | (keys?: string | string[]) => void | Removes state from the Nuxt instance. |
Sources: packages/nuxt/src/app/composables/state.ts:20-30
Data Synchronization Utilities
Nuxt provides utilities to manually manage the cache and state of asynchronous operations, allowing components to synchronize data across the application.
refreshNuxtData and clearNuxtData
- refreshNuxtData: Triggers a re-execution of the fetcher functions for specific keys. If no key is provided, all current data-fetching operations are refreshed.
- clearNuxtData: Clears the cached results and error states for specific keys, allowing for a fresh start.
Sources: packages/nuxt/src/app/composables/asyncData.ts:210-230, test/nuxt/use-async-data.test.ts:182-190
useNuxtData
Provides access to the current cached value and status of an useAsyncData operation without triggering a new fetch. This is useful for optimistic UI updates or accessing data fetched in parent routes.
Sources: packages/nuxt/src/app/composables/asyncData.ts:190-205
Conclusion
The data fetching and state system in Nuxt is a robust framework for managing full-stack reactivity. By combining key-based deduplication in useAsyncData with payload-aware state management in useState, Nuxt eliminates common hydration pitfalls and provides a performant foundation for data-driven Vue applications.
Sources: packages/nuxt/src/app/composables/asyncData.ts, packages/nuxt/src/app/composables/state.ts