react-native - 在graphql中将变量传递给突变的正确语法是什么
问题描述
我有一个反应原生应用程序。
graphql 中将变量传递给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);
})
解决方案
将变量传递给突变的一种方法可能是执行以下操作:
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);
})
并且只要确保variables
里面的对象JSON.stringify
必须匹配 type CustomerCreateInput
。
推荐阅读
- elasticsearch - 比较 Kibana 地图中两个字段的平均值
- javascript - 这个反应组件中的这个调用堆栈有问题吗?
- c++ - 两个模板模板参数,一个需要另一个
- c - 通过在 C 中的引用传递来修改函数内部的字符串
- ios - 为什么 Xcode 13 不惜一切代价忽略设备方向设置?
- bootstrap-5 - 如何重置bootstrap 5 text-muted的效果
- powershell - 如何在 Powershell 中实现二进制哈希字符串的 Base64 URL 安全编码?
- r - 如何在 R 中按日期合并/堆叠观察结果
- react-native - 我如何使用反应原生日期时间选择器
- python - kivy 中的大量小部件 - 优化