useFragment
A reactive composable for reading and watching GraphQL fragments from the Apollo cache in Vue 3.
Quick start
ts
import { useFragment } from '@vue3-apollo/core'
import { gql } from 'graphql-tag'
export const USER_FRAGMENT = gql`
fragment UserFragment on User {
id
name
email
company {
name
}
}
`
const { result, data, complete, error, onResult } = useFragment(USER_FRAGMENT, {
from: 'User:1',
variables: {
withPosts: true
}
})
onResult(({ data, complete }) => {
if (complete) console.log('Fragment ready:', data)
})This composable automatically tracks and updates when the underlying cache data changes.
How it works
- Cache-driven: Reads data directly from the Apollo cache and re-renders when it updates.
- Reactive watching: Automatically resubscribes when
fromorvariables(refs or getters) change. - Type-safe: Exposes a full
resultobject for advanced TypeScript narrowing. - SSR ready: When
prefetchis enabled, fragments are resolved during server-side rendering.
API
Returns
result– Full fragment result includingdata,complete, andmissinginformation. Ideal for TypeScript narrowing.tsconst { result } = useFragment<User>(USER_FRAGMENT, { from: 'User:1' }) if (result.value?.complete) { console.log(result.value.data.name) // ✅ Fully typed } else { console.log(result.value?.missing) // Partial data info }data– Reactive fragment data (DeepPartial<TData>). May be incomplete if fields are missing from cache.complete– Boolean indicating whether the entire fragment is present in the cache.missing– Missing tree info reported by the cache (if any).error– Apollo error object, if an error occurs while reading or watching.start()/stop()– Manually control fragment watching lifecycle.onResult((payload, context) => {})– Triggered when fragment data updates.tsonResult(({ data, complete }, { client }) => { if (complete) console.log('Updated:', data) console.log('Client:', client) })onError((error, context) => {})– Triggered when a cache read or watch error occurs.tsonError((error, { client }) => { console.error('Fragment error:', error) client.clearStore() })
Options (new API)
from– string | object | Ref | getter (required). The source entity to read from cache. Accepts:- A cache ID string (e.g.,
'User:1'). - An entity object with
__typenameand an identifier. - A reactive ref or computed getter returning one of the above.
- A cache ID string (e.g.,
variables– Record<string, any> | Ref | getter. Fragment variables (for fragments with@arguments).fragmentName– string | Ref | getter. Required only if the provided document contains multiple fragments.enabled– boolean | Ref | getter (default:true). Enables or disables fragment watching.optimistic– boolean (default:true). Include optimistic layer when reading from cache.prefetch– boolean (default:true). For SSR: prefetch fragment data during server rendering to avoid hydration flicker.clientId– string. Apollo client identifier if multiple clients are registered.
Overloads
- New (recommended):
useFragment(document, options?) - Legacy (deprecated, still supported):
useFragment({ fragment, ...options })
Legacy usage (deprecated)
ts
// Prefer the new API above. This legacy form remains for backward compatibility.
const { result } = useFragment({
fragment: USER_FRAGMENT,
from: {
__typename: 'User',
id: '123'
},
fragmentName: 'UserFragment'
})Notes
- Watching is based on reference equality of
fromandvariables. Changing references will re-subscribe. - When
fromisnullorundefined, no watching occurs andcompleteisfalse. datais exposed asDeepPartial<TData>since fragments can be partial.- Recommended: Use
resultfor best TypeScript type narrowing. - For SSR, keep
prefetch: truefor smoother hydration.
Types
UseFragmentOptions<TData, TVariables>: Options type for the new API (nofragmentfield).UseLegacyFragmentOptions<TData, TVariables>: ExtendsUseFragmentOptionsand addsfragment. Deprecated — prefer the new API.