Unlock seamless workflows and faster delivery with our latest releases – get the details

Querying a reference field in Sanity and resolving initial value in a document schema

33 replies
Last updated: Apr 25, 2020
I have followed the YouTube tutorial by
user Y
on InitialValue.
From there, I personalise it to my case with this query.

*[_type == 'codeList' && code match 'VT' ]{
      
'_type': 'serviceCodeList',
      
'codeList': {
        
'_ref': _id,
        
'_type': 'reference'
      
}
  
}
giving this response:

"result":[1 item

0:{2 items

"_type":"serviceCodeList"
or
"_type":"codeList"
(I'm not sure)
"codeList":{2 items

"_ref":"56d99a7f-bd55-4cd7-9eeb-d5b65fe63d5e"

"_type":"reference"

But, nevertheless that the query is correct from tutorial, that it works in VISION and is giving me the appropriate
_ref
and
_type
(
"56d99a7f-bd55-4cd7-9eeb-d5b65fe63d5e"
), I run into this error:
Failed to resolve initial Value,

Check developer console for details

I know that this (under) in the schema is working, giving me the
VT
initialValue expected in the studio:
initialValue: {

codeList: {

_ref: '56d99a7f-bd55-4cd7-9eeb-d5b65fe63d5e',

_type: 'reference',

}
`},`①
(contrarily to the tutorial it is not
serviceCodeList
with the document name but simply
codeList
that works)

But this is not a QUERY!
Is there something I am doing wrong?
I mean in the tutorial,
user Y
is doing that for an array and I am adapting that to the schema of a document.
Is it an impossible case?!?
(because it's a document not an array?!?) (probably not because it should work also no?)


⚠️ something else:When it succeed with the direct _ref (driving me to the point like above, see ①), the behaviour of the studio is 
STRANGE.
By that I mean that its 
blinking (eg. bumping on the 9 elements of the promise target) to resolve (like hitting something).
It's very surprising, as in the video with 
user Y
 it is very smooth.
Or is there a way to have that done smooth_ly_ 
like normal?Or it's just my code that is clumsy?
If so what should I change?

Any help very much appreciated ☆
Apr 25, 2020, 9:30 AM
First a pro-tip: You can use triple back-ticks or this function to make a
more readable codeblock
Apr 25, 2020, 9:35 AM
Could you post the schema-code with the initialValue config, so that I better understand what's going on?
Apr 25, 2020, 9:36 AM
yes sure. A minute. Here?
Apr 25, 2020, 9:36 AM
import { RiBusLine } from 'react-icons/ri'


var dateobj = new Date()
dateobj.setHours(7); //réglé à 07h00
var B = dateobj.getHours()
var C = dateobj.getDate()
var D = dateobj.getMonth()
var E = dateobj.getFullYear()

var eventAtSeven = new Date(E,D,C,B,0,0,0)

Date.prototype.addDays = function(days) {
  var date = new Date(this.valueOf());
  date.setDate(date.getDate() + days);
  return date
}

var eventAtSevenToFourDays = eventAtSeven.addDays(4)
var event = new Date()

export default {
  name: 'service',
  title: 'Service',
  icon: RiBusLine,
  description: 'un service Cityvision est un événement plus une offre commerciale',
  type: 'document',
  // description: "représentation de l'affectation prévisionnelle d'un Service Cityvision pour être effectué à une date, une heure, selon un programme représenté code d'affectation en une langue donnée; la représentation elle-même a été publiée depuis une date et une heure données, depuis cette publication son actualité est décrit par un statut: événement prévu, annulé, reporté, reprogrammé, prévu pour se tenir virtuellement en ligne"
  fields: [
    {
      name: 'startDate', // ATTENTION CHANGEMENT PAR RAPPORT À GATSBY
      title: 'Date',
      description: 'Date et Heure de Départ du service Cityvision',
      type: 'datetime', // ATTENTION CHANGEMENT PAR RAPPORT À GATSBY
      options: {
        dateFormat: 'YYYY-MM-DD',
        timeFormat: 'HH:mm',
        timeStep: 15,
      },
    },
    {
      name: 'codeList',
      description: 'Code commercial du service Cityvision (valeur default: VT)',
      title: 'Code List',
      type: 'reference',
      validation: Rule => Rule.required(),
      to: [
        {
          name: 'codeList',
          title: 'Code List',
          type: 'codeList',
        },
      ],
    },
    {
      name: 'lang',
      description: 'Langue parlée durant le service Cityvision (valeur default: ja)',
      title: 'Langue',
      type: 'reference',
      validation: Rule => Rule.required(),
      to: [
        {
          name: 'lang',
          title: 'Langue',
          type: 'lang',
        },
      ],
    },
    {
      name: 'releaseDate', // ATTENTION CHANGEMENT PAR RAPPORT À GATSBY
      description: 'Date de publication du service Cityvision',
      title: 'Date de publication',
      type: 'datetime', // ATTENTION CHANGEMENT PAR RAPPORT À GATSBY
      options: {
        dateFormat: 'YYYY-MM-DD',
        timeFormat: 'HH:mm',
      },
    },
    {
      type: 'string',
      title: 'Status',
      description: 'Status de la publication du service Cityvision',
      name: 'status',
      options: {
        list: [
          {title: 'Scheduled', value: 'EventScheduled'},
          {title: 'Cancelled', value: 'EventCancelled'},
          {title: 'Postponed', value: 'EventPostponed'},
          {title: 'Rescheduled', value: 'EventRescheduled'},
          {title: 'MovedOnline', value: 'EventMovedOnline'},
        ],
        layout: 'radio',
        direction: 'vertical',
      },
    },
  ],
  initialValue:  async () => ({
    startDate: eventAtSevenToFourDays.toISOString(),
    status: 'EventScheduled',
    releaseDate: event.toISOString(),
    codeList: {
      _ref: '56d99a7f-bd55-4cd7-9eeb-d5b65fe63d5e',
      _type: 'reference',
    },
    // codeList: await client.fetch(`// groq
    // *[_type == 'codeList' && code match 'VT' ]{
    //     '_type': 'serviceCodeList',
    //     'codeList': {
    //       '_ref': _id,
     //      '_type': 'reference'
    //     }
    // }
    // `)
    lang: {
      _ref: '236a03a9-d72c-456b-b79b-3eb8ccb1c211',
      // _ref: await client.fetch(`// groq
      // *[_type == 'lang' && name match 'ja' ]{
      //    _id
      // }[0]`),
      _type: 'reference',
    },
  }),
  orderings: [
    {
      title: 'Start Date, New',
      name: 'startDateAsc',
      by: [
        {field: 'startDate', direction: 'asc'}
      ]
    },
  ],
};
Apr 25, 2020, 9:37 AM
export default {
  name: 'service',
  title: 'Service',
  type: 'document',
  fields: [
    {
      name: 'codeList',
      title: 'Code List',
      type: 'reference',
      validation: Rule => Rule.required(),
      to: [
        {
          name: 'codeList',
          title: 'Code List',
          type: 'codeList',
        },
      ],
    },
  ],
  initialValue:  async () => ({
    codeList: {
      _ref: '56d99a7f-bd55-4cd7-9eeb-d5b65fe63d5e',
      _type: 'reference',
    }, // that works!
    // codeList: await client.fetch(`// groq
    // *[_type == 'codeList' && code match 'VT' ]{
    //     '_type': 'serviceCodeList',
    //     'codeList': {
    //       '_ref': _id,
     //      '_type': 'reference'
    //     }
    // }
    // `) Unfortunately that does not!
  ],
};
Apr 25, 2020, 9:41 AM
Does this work?
codeList: await client.fetch(`// groq
    *[_type == 'codeList' && code match 'VT' ][0]{
        '_type': 'serviceCodeList',
        'codeList': {
          '_ref': _id,
          '_type': 'reference'
        }
    }
    `)

Apr 25, 2020, 9:42 AM
short version:
export default {

  name: 'service',
  title: 'Service',
  type: 'document',
  fields: [
    {
      name: 'codeList',
      title: 'Code List',
      type: 'reference',
      validation: Rule => Rule.required(),
      to: [
        {
          name: 'codeList',
          title: 'Code List',
          type: 'codeList',
        },
      ],
    },
  ],
  initialValue:  async () => ({
    codeList: {
      _ref: '56d99a7f-bd55-4cd7-9eeb-d5b65fe63d5e',
      _type: 'reference',
    }, // that works!
    // codeList: await client.fetch(`// groq
    // *[_type == 'codeList' && code match 'VT' ]{
    //     '_type': 'serviceCodeList',
    //     'codeList': {
    //       '_ref': _id,
     //      '_type': 'reference'
    //     }
    // }
    // `) Unfortunately that does not!
  ],
};
Apr 25, 2020, 9:42 AM
I try.
Apr 25, 2020, 9:42 AM
Btw. I recommend using
date-fns
 instead of mutating the
Date
 prototype. That's a pattern that can give you trouble 🙂 https://date-fns.org/docs/addDays
Apr 25, 2020, 9:43 AM
Understood
Apr 25, 2020, 9:43 AM
thank you
Apr 25, 2020, 9:43 AM
No it doesn't.I tried with serviceCodeList
and codeList.
But both are running into this error:

Failed to resolve initial Value,

Check developer console for details
.
Apr 25, 2020, 9:48 AM
what does the developer console say?
Apr 25, 2020, 9:50 AM
I don't know where it is.
Apr 25, 2020, 9:51 AM
are you talking of the browser developer console?
Apr 25, 2020, 9:51 AM
If you're using Chrome
Apr 25, 2020, 9:51 AM
wait, I got it
Apr 25, 2020, 9:51 AM
...
Apr 25, 2020, 9:52 AM
it doesn't seem like you import the client, try
import client from 'part:@sanity/base/client'
in the top of your file
Apr 25, 2020, 9:52 AM
[and you still have to do the
[0]
in your query to return the first document as an object and not an array]
Apr 25, 2020, 9:53 AM
Content has invalid type: 
serviceCodeList
▼Details
Encountered a value of type 
serviceCodeList
.Only content of type 
reference
 are valid here according to schemaThe current value is:
Remove value
Apr 25, 2020, 9:54 AM
codeList: await client.fetch(`// groq
    *[_type == 'codeList' && code match 'VT' ][0]{
          '_ref': _id,
          '_type': 'reference'
    }
    `),

Apr 25, 2020, 9:54 AM
Sorry for the import thing, I had it before, removed it yesterday night...
Apr 25, 2020, 9:54 AM
B I N G O ! ! ! !
Apr 25, 2020, 9:56 AM
T H AN K S ! ! ! !
Apr 25, 2020, 9:56 AM
I feel a lot better now!
Apr 25, 2020, 9:56 AM
Good to hear – did you get why it worked?
Apr 25, 2020, 9:57 AM
It is also very smooth, so P E R F E C T ! ! ! !
Apr 25, 2020, 9:57 AM
from the beginning I had a problem as my references where both codeList leading to confusion.But no I don't really understand the difference with the tutorial except that I don't have the same hierarchy.
In the tutorial Members were placed differently.
Isn't it?
Apr 25, 2020, 9:59 AM
In the tutorial you have to first go to Members and then the reference.In my case, it is possible to go directly to the reference.
do you agree?
Apr 25, 2020, 10:00 AM
Yeah, that is, the members object in the tutorial are objects with more than one field (it has
roles
 and
person
). While you just have a reference. That's why I demonstrate that you should add data manually first, and then try to have the query match the data structure.
Apr 25, 2020, 10:03 AM
user Y
I would like to say that from I was given to see, you are very good in communication, communication being a VERY VERY V E R Y DIFFICULT subject.Please (if you can) I beg you for not keeping any anger that I am not that clever!
I am in the learning curve, but I learn from my mistakes.
«Errare humanum est, sed perseverare diabolicum».
Thank you for the precious time that you offered to give to pay attention to my problem.
I am going from now to change Date to date-fns.
As you are saying: see you in the virtual space!
Apr 25, 2020, 10:11 AM
No worries 🙂 It was I that set this channel topic, so you absolutely should feel safe and OK to ask questions here. 🙇‍♂️
Apr 25, 2020, 10:13 AM

Sanity– build remarkable experiences at scale

Sanity is a modern 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?