3

I have a super simple GraphQl query, but im having trouble to make the query dynamic based on input. Lets say you will get a string in javascript that you want to pass along to the query, how is it done? Take example below, how would i replace the hardcoded string of "3111" on the Sku field in the product but instead inserting the value from the variable myString? I am just getting errors when i try to pass it along.

let myString = "3111"

`query getProductBySku {
        site {
          product(sku: "3111") {
            id
            entityId
            name
            sku
          }
        }
      }`

1 Answer 1

7

Have a look here: https://graphql.org/graphql-js/passing-arguments/

In your case scenario:

var query = `query getProductBySku($sku: String) {
        site {
          product(sku: $sku) {
            id
            entityId
            name
            sku
          }
        }
      }
`;

fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  body: JSON.stringify({
    query,
    variables: { "3111" }, // this refers to SKU
  })
})
  .then(r => r.json())
  .then(data => console.log('data returned:', data));

Basically other than creating a query that allows argument to pass, you need a POST request with the body setup to accomodate the inputs which are expected to be fulfilled

Sign up to request clarification or add additional context in comments.

4 Comments

should it not be variables: { sku : "3111" } ?
@andymccullough yea, I thought so. If you open the link the official doc it reports you can use positional arguments though. Without the need to declare the specific parameter you're referring to.
There is no need for variables object in the body as arg to stringify. Just pass the var to query with ${sku}. It works because of the backticks.
variables: {"sku":"${sku}","var2":"${var2}"},

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.