Search code examples
graphqlshopifyshopify-apiremix.run

Fetching dynamic data - remix run - storefrontapi - graphql


I have having trouble trying to fetch dynamic data on Remix run and the shopify storefront api. I am able to fetch all the products from the API but when I want to get the data of a specific product eg - when you click on one of the products I get the error

message: "Field 'product' doesn't exist on type 'QueryRoot'",

Using the shopify graphql on the website my query works fine but as soon as i try and implement it on remix it does not work

export async function getProduct(slug: any):Promise<any> {
  const variable = {id: slug}
  const URL = `${domain}/api/2021-07/graphql.json`
  const query = `
  query GetProductsById($id: ID!) {

  product(id: $id) {
    title
     featuredImage {
       id
     }
  }
}
  `
  
  
  const options = {
    endpoint: URL,
    method: "POST",
    headers: {
      "X-Shopify-Storefront-Access-Token": storefrontAccessToken,
      "Accept": "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ query, variable })
  }
  
  try {
    const response: Response = await fetch(URL, options);
    const data = await response.json()
    return data
  
  
  } catch (error) {
  
    throw new Error("Products not fetched")
  }
  }

This is the error message

GET /products/Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0LzY5NjQ2MDEzMjM2NjA=?_data=routes%2Fproducts%2F%24slug 200 - - 25.181 ms
[1] {
[1]   errors: [
[1]     {
[1]       message: "Field 'product' doesn't exist on type 'QueryRoot'",
[1]       locations: [Array],
[1]       path: [Array],
[1]       extensions: [Object]
[1]     },
[1]     {
[1]       message: 'Variable $id is declared by GetProductsById but not used',
[1]       locations: [Array],
[1]       path: [Array],
[1]       extensions: [Object]
[1]     }
[1]   ]
[1] } 

Does anyone haven idea what i am doing wrong?


Solution

  • I believe there are two issues here:

    1. product doesn't exist in the Storefront API version you're using (2021-07), that only got introduced in 2021-10. If you can't upgrade you can use node instead, code example below.
    2. Rename variable to variables in your request.
    query getProductById($id: ID!) {
      node(id: $id) {
        ... on Product {
          title
        }
      }
    }