2017-05-18 9 views
1

サブスクリプションでオプティミスティックUIを持つことは意味がありますか?Apollo jsサブスクリプションオプティミスティックUI

だから、基本的には:

addChannelMutation({ 
    variables: { name: eventValue }, 
    optimisticResponse: { 
    __typename: "Mutation", 
    addChannel: { 
     __typename: "Channel", 
     id: data.channels.length, 
     name: eventValue 
    } 
    }, 
    update: (store, { data: { addChannel } }) => { 
    // Read the data from our cache for this query. 
    const data = store.readQuery({ query: channelsListQuery }); 
    // Add our comment from the mutation to the end. 
    data.channels.push(addChannel); 
    // Write our data back to the cache. 
    store.writeQuery({ query: channelsListQuery, data }); 
    } 
}).then(res => {}); 

これは、重複キーの例外をトリガ二度同じ項目を追加します。 楽観主義はサブスクリプションで意味をなさないのですか?

答えて

1

optimisticResponseupdateが応答を受信する前にトリガーします。サーバーが応答すると、updateが再度トリガーされ、楽観的なプレースホルダーが応答に置き換えられます。

サブスクリプションは、サーバーの突然変異が解決されると一度だけ発生します。したがって、本質的にサーバーが応答しているときです。

オプティミスティックUIが含まれておらず、何らかの待ち時間があった場合は、サーバーから応答が送信されるまで結果が表示されません。これは、チャットアプリなどで、送信ボタンをクリックするとすぐにメッセージが表示されない場合など、問題になる可能性があります。彼らは複数回ボタンをクリックし続けるとメッセージをお送りします:Optimisic UIとサブスクリプションを使用する場合/

dupesを戦うために、2つの戦略が含まれます:

:クライアント上dupesため

  1. チェックをあなたのsubscripでupdateQuery内部

    // super simplified dupe doc checker 
    function isDuplicateDocument(newDocument, existingDocuments) { 
        return newDocument.id !== null && existingDocuments.some(doc => newDocument.id === doc.id); 
    } 
    
    addChannelMutation({ 
        variables: { name: eventValue }, 
        optimisticResponse: { 
        __typename: "Mutation", 
        addChannel: { 
         __typename: "Channel", 
         id: data.channels.length, 
         name: eventValue 
        } 
        }, 
        update: (store, { data: { addChannel } }) => { 
        // Read the data from our cache for this query. 
        const data = store.readQuery({ query: channelsListQuery }); 
        if (isDuplicateDocument(addChannel, data.channels) { 
         return; 
        } 
    
        // Add our comment from the mutation to the end. 
        data.channels.push(addChannel); 
        // Write our data back to the cache. 
        store.writeQuery({ query: channelsListQuery, data }); 
        } 
    }).then(res => {}); 
    

    も:updateupdateQuery機能で

    ン:

    subscribeToMore({ 
        ... 
        updateQuery: (previousResult, { subscriptionData }) => { 
        const newChannel = subscriptionData.data.addChannel; 
        // if it's our own mutation 
        // we might get the subscription result 
        // after the mutation result. 
        if (isDuplicateDocument(
         newChannel, previousResult.channels) 
        ) { 
         return previousResult; 
        } 
    
        return update(previousResult, { 
         channels: { 
         $push: [newChannel], 
         }, 
        }); 
        }, 
    
  2. それとも、新しいチャネルの作成者に放出しないように、サーバー上のサブスクリプションを制限することができます。

+0

ありがとうございます。それはまさに私がやっていることです。 –