Data Fetching

Nuxt Statamic provides composables to handle data fetching within your application.

Nuxt Statamic comes with two composables and a fully configured $fetch instance to perform data-fetching: useStatamicApi, useStatamicFetch, useStatamicPage and $api.

In a nutshell:

  • $api is the most barebones way to make a network request.
  • useStatamicApi is a wrapper around $api that provides a comprehensive API interface for interacting with Statamic CMS.
  • useStatamicFetch is a wrapper around useFetch with the $api instance.
  • useStatamicPage is a composable for fetching the current Statamic page data.

When to use what?

$api

  • Use case:
    Server-side requests or inside early lifecycle hooks.

It's most useful when you need to make a server-side network request to a Statamic API endpoint that is not covered by the useStatamicApi or useStatamicPage composables.

useStatamicApi

  • Use case:
    Almost always.

This composable provides a comprehensive API interface for interacting with Statamic CMS. It offers methods to fetch entries, navigations, globals, forms, taxonomies etc.

app/pages/blogs.vue
<script setup lang="ts">
const api = useStatamicApi();
const { data: blogs } = await useAsyncData(
    useStatamicCacheKey("entries", "blogs"),
    () => api.entries("blogs")
);
</script>

useStatamicFetch

  • Use case:
    When you need to fetch data from a Statamic API endpoint that is not covered by the useStatamicApi or useStatamicPage composables.

This composable is a wrapper around the useFetch composable that uses the modules $api instance as its $fetch instance. This allows you to call any endpoint from the Statamic API you want.

app/pages/blogs/[...slug].vue
<script setup lang="ts">
const { data } = await useStatamicFetch("/tenants");
</script>

useStatamicPage

  • Use case:
    When you need to fetch the current Statamic page data based on the current route (URI).

This composable will automatically fetch the current Statamic page data based on the current route (URI).

It will also throw errors when a page is not found, this will need to be handled by the useStatamicPageErrorHandler composable afterwards.

app/pages/[...slug].vue
<script setup lang="ts">
const { data, error } = await useStatamicPage();
useStatamicPageErrorHandler(error);
</script>

Default requests

The module also adds default requests for the following endpoints/ resources:

  • Navigations
  • Globals
  • Redirects - When enabled in the module configuration
  • Sitemap - When enabled in the module configuration

These requests are cached by default for 1 or more hours. You can configure the cache duration by using the server option.

See the server configuration for more information on how to configure the cache duration.

The data of these requests will also be automatically updated whenever one of the cache parameters changes. See useStatamicCacheKey for more information.