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.
<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>
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.
export function useStatamicPageData<DataT = any>(): Ref<DataT | undefined> {
return useNuxtData(
useStatamicCacheKey("page", useStatamicPageUri()).value
)?.data as Ref<DataT | undefined>;
}
declare function useStatamicCacheKey(
resource: StatamicApiResourceType,
identifier: MaybeRef<string | number>,
context: MaybeRef<Record<string, any> | string>,
asyncDataOptions: MaybeRef<AsyncDataOptions<any, Record<string, any>>>,
): ComputedRef<string>
{siteIdentifier}:{resource}:{identifier}::{contextHash}:{asyncDataOptionsHash}
The
siteIdentifieris the site returned byuseStatamicSite.