Skip to content

Commit

Permalink
Refactor useCraftQuery composable to use useAsyncData
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelreichor committed Nov 7, 2024
1 parent 27f6314 commit 515ab3c
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 24 deletions.
5 changes: 5 additions & 0 deletions .changeset/eighty-files-grow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"nuxt-craftcms": patch
---

Refactor useCraftQuery composable to use useAsyncData for more control
15 changes: 6 additions & 9 deletions playground/app.vue
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ref } from 'vue'
import { useCraftQuery } from '../src/runtime/composables/useCraftQuery'
const data = ref()
const news = ref()
const entryQuery = useCraftQuery('entries')
// Fetch in setup function
onMounted(async () => {
const { data: initialData, error: initialError } = await entryQuery.slug('home').one()
const { data: initialData, error: initialError } = await entryQuery.slug('home').one()
if (initialError.value) {
console.error(initialError.value)
}
if (initialError.value) {
console.error(initialError.value)
}
data.value = initialData.value
})
console.log(initialData.value)
// Fetch on clientside
async function loadNews() {
Expand Down
2 changes: 1 addition & 1 deletion playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export default defineNuxtConfig({
modules: ['../src/module'],

craftcms: {
baseUrl: 'https://backend-craftcms.ddev.site',
baseUrl: 'https://backend-craftcms.ddev.site:8443',
},

devtools: { enabled: true },
Expand Down
21 changes: 7 additions & 14 deletions src/runtime/composables/useCraftQuery.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,9 @@
import type { Ref } from 'vue'
import type { ElementType } from 'js-craftcms-api'
import { useCraftUrlBuilder } from 'vue-craftcms'
import { useFetch } from '#imports'
import { useAsyncData } from '#imports'

interface FetchResult<T = unknown> {
data: Ref<T | null>
error: Ref<unknown | null>
}

async function fetchFn(url: string): Promise<FetchResult> {
const { data, error } = await useFetch(url)
return { data, error }
function fetchFn(url: string) {
return useAsyncData(`craftcms:${url}`, () => $fetch(url))
}

export function useCraftQuery<T extends ElementType>(elementType: T) {
Expand All @@ -19,14 +12,14 @@ export function useCraftQuery<T extends ElementType>(elementType: T) {
return {
...queryBuilder,

async one() {
one() {
const url = queryBuilder.buildUrl('one')
return await fetchFn(url)
return fetchFn(url)
},

async all() {
all() {
const url = queryBuilder.buildUrl('all')
return await fetchFn(url)
return fetchFn(url)
},
}
}

0 comments on commit 515ab3c

Please sign in to comment.