我有一个 Relay 突变,它创建一个帖子并将其添加到帖子列表中。在将突变发送到我的 GraphQL 服务器之前,乐观更新会将帖子的标题和 url 添加到列表中。我的问题是,当突变失败或无法完成时,乐观更新会自动从列表中删除。有没有办法捕捉和处理失败的突变,以便我可以向用户显示某种消息,表明帖子无法保存?
我的中继突变:
import Relay from 'react-relay';
class CreatePostMutation extends Relay.Mutation {
getMutation () {
return Relay.QL`
mutation {
createPost
}
`
}
getVariables() {
return {
title: this.props.title,
url: this.props.url
}
}
getFatQuery() {
return Relay.QL`
fragment on CreatePostPayload {
postEdge,
store {
id
}
}
`;
}
getConfigs() {
return [{
type: 'RANGE_ADD',
parentName: 'store',
parentID: this.props.store.id,
connectionName: 'allPosts',
edgeName: 'postEdge',
rangeBehaviors: {
'': 'prepend'
}
}]
}
getOptimisticResponse() {
return {
postEdge: {
node: {
title: this.props.title,
url: this.props.url
}
}
}
}
}
export default CreatePostMutation;
我的 PostForm React 组件:
import React from 'react';
import Relay from 'react-relay';
import CreatePostMutation from '../../mutations/create_post';
class PostForm extends React.Component {
handleSubmit = (e) => {
e.preventDefault();
let {relay, store} = this.props;
let {title, url} = this.refs;
relay.commitUpdate(
new CreatePostMutation({
title: title.value,
url: url.value,
store
})
);
// clear values
title.value = '';
url.value = '';
}
render () {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input name="title" placeholder="Title" ref="title" />
<input name="url" placeholder="URL" ref="url" />
<input type="submit" />
</form>
</div>
)
}
}
export default PostForm;