Discussion on setting up initial value templates in Sanity.io, with a focus on an async function returning the wrong value.

6 replies
Last updated: Aug 10, 2022
Hi everyone,Hoping to get some guidance on initial value templates, in particular the method under ‘Define Multiple Templates’. I’m trying to set up a template that grabs the latest record from a particular document type (‘series’) and uses it as a reference for one of my fields, using an asynchronous function, but I’m just unable to get my code right. The result is the wrong value for the property - where it expects a reference I’m getting `the current value (function): undefined`I would love some input into how to amend this async function to return what I’m after! Code in the thread below.
Aug 9, 2022, 2:58 PM
import T from '@sanity/base/initial-value-template-builder'
import sanityClient from 'part:@sanity/base/client';

const client = sanityClient.withConfig({apiVersion: '2022-03-13'})

export default [
  ...T.defaults(),

  T.template({
    id: 'communion-service',
    title: 'Communion Service',
    schemaType: 'service',
    icon: GiJeweledChalice,
    value: {
      serviceDate: nextDay(0),
      currentSeries: async () => {
        const seriesId = await client
          .fetch(`*[_type == 'series' && !(_id in path("drafts.**"))] | order(_createdAt desc)[0]._id`)
        return {_type: 'reference', _ref: seriesId };
      },
     }
  })
]
Aug 9, 2022, 2:59 PM
So all I want from the query is the ID string of the most recently created ‘series’, so I can return it in the object on my return line. Using Vision, that’s exactly what I get, but I’m a bit sloppy on async requests, and am likely not structuring things correctly, so I’m ending up with the error as stated in my initial post.
Aug 9, 2022, 3:01 PM
Unfortunately no matter what I do, I’m unable to log out the result of that fetch request in a .then(response => console.log(response) chain, so can’t determine if the fetch is actually happening.
Aug 9, 2022, 3:02 PM
I wonder if you need to move your async function up to value? Maybe try:
export default [
  ...T.defaults(),

  T.template({
    id: 'communion-service',
    title: 'Communion Service',
    schemaType: 'service',
    icon: GiJeweledChalice,
    value: async () => {
      const seriesId = await client
          .fetch(`*[_type == 'series' && !(_id in path("drafts.**"))] | order(_createdAt desc)[0]._id`)
        
      return {
        serviceDate: nextDay(0),
        currentSeries: {_type: 'reference', _ref: seriesId }
      }
  }})
]
Aug 9, 2022, 4:47 PM
Alright! We have winner. Thanks so much
user M
Honestly, the 7th line of the example code should have been clear enough for me, given the return object includes the key and value… but trying to program at midnight didn’t serve me well yesterday… haha
Aug 10, 2022, 1:33 AM
Awesome! So glad it worked!
Aug 10, 2022, 3:13 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?