Shopify GraphQL Using Fetch API, Returns Empty Json, No Errors

- 1 answer

Trying to just fetch the name of my store in a React component using the Fetch API and GraphQL endpoint of Shopify.

I created a Shopify store, gave permissions to the Storefront API and crafted this in my componentDidMount() section of my react component.

let query = '{ shop { name } }';

fetch('', {
        method: "POST",
        headers: {
            "Content-Type": "application/graphql",
            "X-Shopify-Storefront-Access-Token": "<My API Key>"
        body: JSON.stringify(query),
  .then(function(myJson) {

My console log output:

"{ shop { name } }"
App.js:21 fetched
App.js:22 {}

I'm not even getting an error, makes me think it's going through possibly? But can't find my shop's name in this query?

I think overall I don't know best practices to craft a GraphQL query in Javascript. Do I make a large string or just a normal, JSON to represent it?

*Also I'm trying not to use a graphQL client library at the moment, and just to use fetch API.



You can't read the response the fetch call resolves to directly like that. Instead, you should call whatever method is appropriate for the mime type you're fetching. From the Mozilla docs:

Once a Response is retrieved, there are a number of methods available to define what the body content is and how it should be handled.

For JSON, you call the json method. You can see more examples here. That means your code should look more like this:

  .then(res => res.json())

Also, please bear in mind that you don't need to stringify your query. You should probably use the application/json content type (which is standard, I believe) and wrap your query inside an object like this.

body: { query },

Then if you have variables, these can be included in the same object:

body: { query, variables }