Data Fetching
useFetch
This is the main form of fetching data from the backend. This can only be used in pages. Can be awaited.
<script setup>
const { data: count } = await useFetch('/api/count')
</script>
<template>
Page visits: {{ count }}
</template>
useLazyFetch
This is the same as useFetch but does not block navigation, so you need to handle the case where data is null while still fetching. It does also provide a pending flag to know when the data is loading.
const { pending, data: posts } = useLazyFetch('/api/posts')
useAsyncData
Can be used in a component, composable, or page. The first argument is a key for the data. The main different between this and useFetch is that this provides some more control for the developer.
const { data } = await useAsyncData('count', () => $fetch('/api/count'))
useAsyncLazyData
Again, same as useAsyncData but you need to handle the case where the data is null.
const { pending, data: count } = useLazyAsyncData('count', () => $fetch('/api/count'))
Refreshing data
All of these functions also return a refresh
property that can be called to refetch the data.
const { data: users, pending, refresh, error } = await useFetch(() => `users?page=${page.value}&take=6`, { baseURL: config.API_BASE_URL }
function previous(){
page.value--;
refresh();
}
function next() {
page.value++;
refresh();
}
You can also refresh all data for a given key with refreshNuxtData
. If no key is specified, it will refresh all queries.
const { pending, data: count } = useLazyAsyncData('count', () => $fetch('/api/count'))
const refresh = () => refreshNuxtData('count')
Trimming data
You can use the pick
option to limit what pieces of data get returned on the request so you only get the fields you need.
const { data: mountain } = await useFetch('/api/mountains/everest', { pick: ['title', 'description'] })
More useFetch documentation
function useFetch(
url: string | Request,
options?: UseFetchOptions
): Promise<DataT>
type UseFetchOptions = {
key?: string,
method?: string,
params?: SearchParams,
body?: RequestInit['body'] | Record<string, any>
headers?: {key: string, value: string}[],
baseURL?: string,
server?: boolean
lazy?: boolean
default?: () => DataT
transform?: (input: DataT) => DataT
pick?: string[]
}
type DataT = {
data: Ref<DataT>
pending: Ref<boolean>
refresh: () => Promise<void>
error: Ref<Error | boolean>
}