Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
How to use Javascript Variable in GraphQL Query Variables?

I'm using a fetch to retrieve data via a GraphQL request. However this code is on a template and my product IDs change depending on what page you're on. I'd like to pass a variable to the GraphQL variables section but I keep getting Bad Request errors. When I use a static int number in my query it works fine, but I need this to variable (currentProductId) to change.

Here's my code:

fetch("/graphql", {
  method: "POST",
  credentials: "same-origin",
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer {{settings.storefront_api.token}}",
  },
  body: JSON.stringify({
    query: `query ExtendedProductsById(
  $productIds: [Int!]
  # Use GraphQL Query Variables to inject your product IDs
) {
  site {
    products(entityIds: $productIds, first: 5) {
      edges {
        node {
          name
          variants(first: 25) {
            edges {
              node {
                sku
                prices {
                  price {
                    currencyCode
                    value
                  }
                }
                defaultImage {
                  url(width: 1000)
                }
              }
            }
          }
          productOptions(first: 5) {
            edges {
              node {
                entityId
                displayName
                isRequired
                ... on CheckboxOption {
                  checkedByDefault
                }
                ... on MultipleChoiceOption {
                  values(first: 10) {
                    edges {
                      node {
                        entityId
                        label
                        isDefault
                        ... on SwatchOptionValue {
                          hexColors
                          imageUrl(width: 200)
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
`,
    variables: { productIds: [currentProductId] },
  }),
})
  .then((response) => response.json())
  .then((data) =>
    setIndividualVariantPricing(
      data.data.site.products.edges[0].node.variants.edges
    )
  );

The issue in question is in this line

variables: { productIds: [currentProductId] },

This gives me a 400 Bad Request error, but this one below doesn't.

variables: { productIds: [12345] },

Above my fetch request I have a Handlebars variable that updates this to be the current product ID, but I console.logged and checked to make sure that it is an integer and would be feeding this correctly to my fetch. I'm not sure what the issue is or how to correctly pass a Javascript variable into my query body.

var currentProductId = "{{product.id}}"; // 12345
parseInt(currentProductId);
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda