graph - 如何访问 Apollo 的 useMutaion 响应
问题描述
当我使用 useMutation 挂钩进行突变时,我可以控制台记录我的数据,但我无法将数据对象保存在 localState 中。我不知道我错过了什么。任何帮助表示赞赏。
我的代码如下:
//Schema file
startTest(identifier: String): TestResponse
突变有效载荷如下:
type TestResponse {
errorCode: Int
errorMessage: String
success: Boolean
transactionId: ID
version: Int
}
在解析器中,我硬编码了以下数据返回:
startTest(_, { identifier }) {
console.log("hello from server");
return {
errorCode: 0,
errorMessage: null,
success: true,
transactionId: "d2984911-bbc4-4e6a-9103-96ca934f6ed3",
version: 0,
};
},
在组件文件夹中,我通过单击按钮触发了突变。
const [startTestt, { loading, error, data }] = useMutation(
START_FIRE_DAMPER_TEST,
{
onCompleted: ({ startFireDampersTest }) =>
console.log(startFireDampersTest.success),
useState(startFireDampersTest.success)
},
{
onError: () => console.log("error!"), // never gets called
}
);
console.log(result); // undefined
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
if (data && data.startFireDampersTest)
return (
<div>
<p>Success!</p>
<pre>{JSON.stringify(data, null, 2)}</pre> // I can see string object but how to render the element of the object inside the component??
</div>
);
const triggerTest = () => {
startTest({ variables: { identifier: "0000000" } });
};
return (
<>
<Banner />
<button onClick={triggerTest}>Click to Delete Buck</button>
</>
);
我需要访问从突变返回的返回数据以供以后使用。测试响应/有效负载与要更新的任何其他查询或类型无关。它只包含测试的状态和我需要保存在本地状态或可能在组件中呈现它的其他关键值。
解决方案
You already have a useState inside your onCompleted
, you'd just need to write properly. Assuming the useState
is a call to the a React's useState
hook, then you're probably just need to move the initialization of your state to your component.
const [isSuccess, setIsSuccess] = useState(false);
const [startTestt, { loading, error, data }] = useMutation(
START_FIRE_DAMPER_TEST,
{
onCompleted: ({ startFireDampersTest }) =>
console.log(startFireDampersTest.success),
setIsSuccess(startFireDampersTest.success)
},
{
onError: () => console.log("error!"), // never gets called
}
);
推荐阅读
- pandas - 将一列文本转换为段落
- git - Git Bash 第一次运行。目录 \drivers\etc 不存在
- javascript - Javascript 警报导致页面内容消失
- javascript - 在反应材料表组件中获取异步数据
- python - 在 django 中创建新模型时所有模型都会重置
- python-3.x - 如何python删除不需要的图标字符
- sql - 使用身份而不是顺序时的随机数
- maxmind - Graylog geoip 没有显示地图上的所有位置
- c# - 连接到 Redshift 集群时出错 - Npgsql.PostgresException: 28000: no pg_hba.conf entry for host
- r - remove groups with different count within a group - data.table in R