πŸ‘€ See Sanity in action: Watch product demo now β†’

Custom GROQ Request in the Preview / Prepare Functions

5 replies
Last updated: Jul 25, 2020
Hi, is it possible to make a custom groq request in the preview / prepare functions? Considering the following code:
export default {
    name: 'singleImage',
    title: 'Single image',
    type: 'object',
    fields: [
        {name: 'image', type: 'image'}
    ],
    preview: {
        select: {
            image: 'image'
        },
        prepare: ({image}) => {
            console.log(image)
            // todo: get image original filename
            return {
                title: 'Single image',
                media: image
            }
        }
    }
}
I'd like to get the original filename of the image field. Accessing it via the select object will only return its
_ref
and
_type
. I would also need to access references field name and more.
Jul 16, 2020, 9:02 PM
Hi
user R
!
In
select
you can dot into references to get their values (https://www.sanity.io/docs/previews-list-views#preview-using-fields-from-referenced-documents-dcbbdb0ec3aa )
So something like this should to it

select: {
   'filename': 'image.asset.originalFilename'
}
Jul 17, 2020, 7:12 AM
Ok that's great. Thanks
Jul 17, 2020, 8:16 AM
Just a quick issue I went through: when requesting
asset.originalFilename
and
asset
in
select
obj, the media won't be loaded. Requesting
asset.originalFilename
seems to modify the content of the media prop, what could be done here?
export default {
    title: 'Image',
    name: 'imageAlt',
    type: 'image',
    preview: {
        select: {
            title: 'asset.originalFilename',
            media: 'asset'
        }
    }
}
Jul 23, 2020, 12:01 PM
I think you need to use the
prepare
function as well. See the example in the link above.
Jul 23, 2020, 5:19 PM
The issue is exactly the same with
prepare
. We can also see that the media object returned is different when we request
asset.originalFilename
Jul 25, 2020, 10:25 AM

Sanity.io – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Categorized in