Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda