7

I am trying to perform a very basic search query with Sanity CMS. This is how the person schema I've created looks like:

export default {
  title: "Person",
  name: "person",
  type: "document",
  fields: [
    {
      title: "Name",
      name: "name",
      type: "string",
    }
  ]
}

I have entered two different Person data. And this is how I try to fetch the data:

const client = sanityClient({
  projectId: 'siaj5ql4',
  dataset: 'production',
  useCdn: true
})

const query = '*[_type == "person"]'

client.fetch(query).then(person => {
  console.log(person)
})

But I get an empty array like so in the console: [] There is no error or anything. Any ideas on this simple task?

dotnetCarpenter
  • 10,019
  • 6
  • 32
  • 54
user1449456
  • 502
  • 1
  • 5
  • 19
  • 1
    The Sanity command line is a good tool for debugging issues like this. Bring up your terminal and cd to the folder where your code is running from. Type the following: `sanity documents query '*[_type=="person"]'`. Do you get any results? – thomax Jul 31 '18 at 09:41
  • @thomax Yes, I do. I also tried the exact same query on `vision` which is a sanity plugin for performing queries and it also returns the expected data. – user1449456 Jul 31 '18 at 09:44

1 Answers1

6

There are two common reasons for this:

  1. The dataset is private and the client is not configured with a token.
  2. The documents you expect to see is not published (drafts are private by default) and the client is not configured with a token.

Also note that the CDN can not be used with private datasets and/or access token.

bjoerge
  • 246
  • 2
  • 5
  • 1
    You're right, the dataset was private and setting it public solved the problem. Are there any downsides with setting the dataset public when the CORS Origins are limited to specific URLs? – user1449456 Jul 31 '18 at 09:46
  • 2
    Glad it solved it for you! Making the dataset public means every published document in your dataset is publicly readable (CORS only matters in a browser context, and does not restrict anyone from e.g. crawling your dataset for all public documents). – bjoerge Jul 31 '18 at 09:55