See Sanity in action 👀 Join us for a live product demo + Q&A →

Trouble querying data with GraphQL in a JavaScript project

5 replies
Last updated: Jul 22, 2021
Hi Everyone!
This is my very first experience with sanity; and im stuck! Any help would be much appreciated!

I have a basic schema and have written a query that reurns the data i would expect it to return in graphQL playground


{
	allTransfer {
		_id
	}
}

But when I use that same query in a javascript project; the only result I get back is an empty object.

const getData = async () => {
      const data = await cms.fetch(`{
        allTransfer {
          _id
        }
      }`);
      console.log(data); //eslint-disable-line
    }

can anybody point me in the direction of what I'm doing wrong? :(
Jul 22, 2021, 6:43 PM
is your dataset private? could it be that you need to pass a token along to the API? (this is a guess) https://www.sanity.io/docs/http-auth
Jul 22, 2021, 6:58 PM
hey, no its a public dataset. I'm wondering if i need to tell sanityClient.fetch that I am using graphql rather than GROC?
Jul 22, 2021, 7:02 PM
is your dataset private? could it be that you need to pass a token along to the API? (this is a guess) https://www.sanity.io/docs/http-auth
Jul 22, 2021, 6:58 PM
ah i think i get it now. the
sanitClient.fetch
method does not actually work with GraphQL. if you want to query with GraphQL, i would recommend using a graphql client or making the http GraphQL request yourself.
here are some graphql clients:

https://github.com/choojs/nanographql (very simple, very lightweight, good for server-fetching or pre-rendering use)
https://www.apollographql.com/docs/react/ (react client-oriented data framework but popular)the first one is probably what you want though
Jul 22, 2021, 7:14 PM
oooh i see! thankyou!!
Jul 22, 2021, 7:15 PM

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.