@favorodera/nuxt-request
v1.0.0
Published
Reactive wrapper around $fetch with lifecycle hooks and status tracking.
Maintainers
Readme
@favorodera/nuxt-request
Reactive wrapper around $fetch with lifecycle hooks and status tracking.
Features
- Reactive state:
data,status,error - Lifecycle hooks:
onPending,onSuccess,onError immediateoption to auto-run on creation- Fully typed with TypeScript
Install
npm i @favorodera/nuxt-requestUsage
const { data, status, error, execute } = nuxtRequest<{ id: number }>(
'/api/example',
{
method: 'GET',
immediate: true,
onPending: () => console.log('loading...'),
onSuccess: (data) => console.log('ok', data),
onError: (error) => console.error('failed', error),
}
)
// Later you can rerun with overrides
await execute({ query: { page: 2 } })API
type Status = 'idle' | 'pending' | 'success' | 'error'
type Hooks<DataT, ErrorT> = {
onPending?: () => void | Promise<void>
onSuccess?: (data: DataT) => void | Promise<void>
onError?: (error: FetchError<ErrorT>) => void | Promise<void>
}
type Options<DataT, ErrorT> = Hooks<DataT, ErrorT> & NitroOptions & {
immediate?: boolean
}
function nuxtRequest<DataT = unknown, ErrorT = unknown>(
request: NitroRequest,
options?: Options<DataT, ErrorT>
): {
data: Ref<DataT | undefined>
status: Ref<Status>
error: Ref<OError<ErrorT> | undefined>
execute: (patch?: Options<DataT, ErrorT>) => Promise<DataT>
}Notes:
execute()merges the initialoptionswith thepatchusing a deep merge for plain objects, replaces arrays and primitives.- When
immediateis true, the request runs once on creation; errors are exposed viaerror.
License
MIT © Favour Emeka
