useStatamicCacheKey

Gitlab
Generates a unique cache key for Statamic API requests to enable efficient data caching and deduplication.
Added since: v1.0.0
Last changed:

Usage

The useStatamicCacheKey composable is used to generate a formatted cache key that is used to cache the data fetched from the Statamic API.

The main benefit of using this composable is that it will automatically generate and update a cache key composed of the provided parameters. This means that you can easily cache the data fetched from the Statamic API and reuse it across different pages and components.

Since Nuxt v3.17 introduced reactive keys, using this composable will automatically refetch the data whenever any of the provided parameters change.

Basic example

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

// The cached data can be easily retrieved like so:
const { data } = useNuxtData(useStatamicCacheKey("entries", "blogs"));
</script>

Advanced example

In our useStatamicPageData composable, we use the useStatamicCacheKey along with the useStatamicPageUri composable to generate a cache key for the page data, which we provide to the useNuxtData that will return the cached data.

runtime/composables/useStatamicPageData.ts
export function 
useStatamicPageData
<
DataT
= any>():
Ref
<
DataT
| undefined> {
return
useNuxtData
(
useStatamicCacheKey
("page",
useStatamicPageUri
()).value
)?.
data
as
Ref
<
DataT
| undefined>;
}

Type Definition

declare function 
useStatamicCacheKey
(
resource
:
StatamicApiResourceType
,
identifier
:
MaybeRef
<string | number>,
context
:
MaybeRef
<
Record
<string, any> | string>,
asyncDataOptions
:
MaybeRef
<
AsyncDataOptions
<any,
Record
<string, any>>>,
):
ComputedRef
<string>

API Reference

Params

The Statamic resource type or custom endpoint string
identifier
MaybeRef<string | number> required
A unique identifier for the specific resource instance (e.g., collection handle, entry slug, page path)
context
MaybeRef<Record<string, any> | string>
Optional context object or string that affects the request (e.g., query parameters, filters)
asyncDataOptions
MaybeRef<AsyncDataOptions<any, Record<string, any>>>
Optional AsyncData options that affect caching behavior (e.g., pick, transform)

Return Value

ComputedRef<string>
The computed reference to the cached data.

Following the format:
{siteIdentifier}:{resource}:{identifier}::{contextHash}:{asyncDataOptionsHash}

The siteIdentifier is the site returned by useStatamicSite.

Changelog

v1.0.0

on

#407d36db

-

feat: released initial version of nuxt-statamic