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);