reactjs - How to pass javascript variable to graphql query? - Stack Overflow

I have a super simple GraphQl query, but im having trouble to make the query dynamic based on input. Le

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
          }
        }
      }`

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
          }
        }
      }`
Share Improve this question asked Dec 23, 2021 at 10:13 ScreamoIsDeadScreamoIsDead 3871 gold badge3 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

Have a look here: https://graphql/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 acodate the inputs which are expected to be fulfilled

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745048343a4608232.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信