2016-07-31 5 views
0

私は投稿を作成し、それを投稿リストの前に追加するRelay突然変異を持っています。楽観的な更新は、突然変異がGraphQLサーバーに送信される前に、投稿のタイトルとURLの前にリストを追加します。私の問題は、突然変異が失敗した場合や完了できない場合、そのオプティミスティックアップデートが自動的にリストから削除されることです。失敗した突然変異を捕捉して処理する方法はありますか?そのため、ユーザーにポストを保存できないことを示す何らかのメッセージを表示できますか? commitUpdateの呼び出し中に突然変異の失敗を処理するためのコールバックを提供し、あなたのPostFormコンポーネントのhandleSubmit機能でリレーで失敗した突然変異を捕捉して処理する方法は?

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; 

答えて

2

マイリレー変異:

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は、コンポーネントに反応

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にあります。

上記の方法を使用すると、システムエラー(例外など)が発生することにご注意ください。また、ユーザーの入力に問題が発生した場合は、ユーザーエラー(例:検証エラー)を1つだけ受け取ることもできます。すべてのユーザーエラーを一緒に受信したい場合は、この優秀な記事で提案されているアプローチ、つまりValidation and User Errors in GraphQL Mutationsを実行することを検討してください。

関連する問題