useSanctumFetch
Usage
Besides useSanctumClient you can directly send a request by using a module-specific
version of fetch composable - useSanctumFetch.
This composable implements a similar interface to useFetch/useAsyncData,
so you can check more details here.
Composable accepts 4 arguments:
- endpoint URL to call
SanctumFetchOptionsto pass to the Sanctum client (ofetch)AsyncDataOptionsto pass touseAsyncDataunder the hood- request
keyfor reactivity and sharing state (optional)
FetchOptions are not available in SanctumFetchOptions due to misbehaviour
on override by the user. You should set them only by using
the module configuration or Nuxt hooks. Unavailable properties:baseUrlcredentials,redirect,retryonRequest,onRequestErroronResponse,onResponseError
const { data, status, error, refresh } = await useSanctumFetch('/api/users')
// or
const { data, status, error, refresh } = await useSanctumFetch(
'/api/users',
{
method: 'GET',
query: {
is_active: true,
},
},
{
pick: ['id'],
},
'my-request-key',
)
You can also use type casting to work with the response as an interface:
interface MyResponse {
name: string
}
const { data } = await useSanctumFetch<MyResponse>('/api/endpoint')
const name = data.value.name // augmented by MyResponse interface
Reactive parameters
If you want to use reactive parameters for the query, you should pass SanctumFetchOptions as a function
to recalculate values on a new request
const page = ref(1)
const { data } = await useSanctumFetch(
'/api/posts',
() => ({
params: {
page: page.value, // reactive value
}
}),
{
watch: [page],
},
)
Once page value changes, the data will be refetched automatically, and the new value will be passed in query parameters.
Reactive URL/key
You can also provide a reactive fetch key in order to trigger request once it changes:
const currentUser = ref(1)
const userUrl = computed(() => `/api/users/${currentUser}`)
const { data } = await useSanctumFetch(
userUrl,
{
// request params if needed
},
{
// async params if needed
},
userUrl
)
If currentUser value changed, then the request will be made automatically and
the URL will contain reflected reactive value.
useSanctumFetch uses useAsyncData composable behind the scenes,
so the behavior is different from useFetch.