I need a reusable Nuxt component that fetches some data from Sanity.io. I'm using the @nuxtjs/sanity package, so the query looks like this:
import { groq } from '@nuxtjs/sanity'
const query = groq`*[_type == "article"][0].title`
export default {
async fetch() {
const result = await this.$sanity.fetch(query)
this.title = result
},
data: () => ({ title: '' }),
}
But if I try to use a variable as a placeholder inside the query template literal as is recommended (${placeholder}) it wouldn't work.
This doesn't work:
const placeholder = 'article'
const query = groq`*[_type == ${placeholder}][0].title`
EDIT
In the Github repository example of the Sanity module, they use this code to achieve what I was looking for:
import Vue from 'vue'
import { groq } from '@nuxtjs/sanity'
const query = groq`*[_type == "movie" && slug.current == $slug][0] {
title,
releaseDate,
castMembers[] {
characterName
},
overview
}`
interface QueryResult {
title: string
releaseDate: string
castMembers: Array<{ characterName: string }>
overview: any[]
}
export default Vue.extend({
components: {
LocalSanityImage: SanityImage,
},
async fetch () {
const movieDetails = await this.$sanity.another.fetch<QueryResult>(query, {
slug: this.$route.params.slug,
})
this.details = movieDetails
},
data: () => ({ details: null as null | QueryResult }),
})
It's a shame that those solutions don't appear in the documentation.
Why they are importing Vue? Do those params work with the code example in the documentation?