如何捕获和处理中继失败的突变?

时间:2016-07-31 14:20:48

标签: reactjs graphql relayjs relay

我有一个Relay变种,它会创建一个帖子并将其预先添加到帖子列表中。在将变异发送到我的GraphQL服务器之前,乐观更新会将帖子的标题和网址添加到列表中。我的问题是,当突变失败或无法完成时,该乐观更新将自动从列表中删除。有没有办法捕获和处理失败的突变,所以我可以向用户显示某种消息,表明该帖子无法保存?

我的接力突变:

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;

1 个答案:

答案 0 :(得分:2)

PostForm组件的handleSubmit函数中,提供回调以在调用commitUpdate时处理突变失败:

const onFailure = (transaction) => {
    // Notify user that the post could not be added.
};
const onSuccess = () => {
    console.log('Post added.')
};
relay.commitUpdate(
    new CreatePostMutation({
        title: title.value,
        url: url.value,
        store
    }),
    {onFailure, onSuccess}
);

您可以在Relay mutation API documentation中找到一个示例。

请注意,如果您使用上述方法,则会收到系统错误(例如,抛出异常)。如果您因用户输入问题而抛出错误,您也只能收到一个用户错误(例如,验证错误)。如果您想要同时收到所有用户错误,可以考虑采用这篇优秀文章中建议的方法:Validation and User Errors in GraphQL Mutations