简体   繁体   中英

What is the correct syntax to pass variable into mutation in graphql

I have a react native app.

What is the correct syntax in graphql to pass variable into customerCreate ?

const url = 'https://xxxx.myshopify.com/api/graphql';
const query = `
    var variable = {
          "input": {
          "email": "test@test.com",
          "password": "pass"
          }
    }

    mutation customerCreate($input: CustomerCreateInput!) {
      customerCreate(input: $input) {
        userErrors {
          field
          message
        }
        customer {
          id
        }
      }
    }
`;
fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: query }),
})
.then(res => res.json())
.then(res => console.log(res.data));
.catch(err => {
    console.log('-- gql err --')
    console.error(err);
})

A way to pass variables into mutation could be by doing something like:

const url = 'https://xxxx.myshopify.com/api/graphql';
const query = `
    mutation customerCreate($input: CustomerCreateInput!) {
      customerCreate(input: $input) {
        userErrors {
          field
          message
        }
        customer {
          id
        }
      }
    }
`;
fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ 
        query: query,
        variables: {
           input: {
             email: "test@test.com",
             password: "pass"
           }
        }, 
    }),
})
.then(res => res.json())
.then(res => console.log(res.data));
.catch(err => {
    console.log('-- gql err --')
    console.error(err);
})

And just make sure the variables object inside JSON.stringify have to match the type CustomerCreateInput .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM