Apollo js订阅乐观UI

Luc*_*gon 3 subscriptions apollo reactjs optimistic-ui

使用带有订阅的乐观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 => {});
Run Code Online (Sandbox Code Playgroud)

它将同一项添加两次,触发重复的密钥异常。因此,乐观的ui对于订阅是否有意义?

srt*_*r22 6

optimisticResponseupdate在服务器收到响应之前触发。然后,当服务器响应时,update将再次触发并用响应替换乐观的占位符。

只有在服务器突变解决后,订阅才会发出,因此实质上是在服务器响应时发出。

如果您不包括Optimistic UI,并且有任何延迟,那么直到服务器发送响应后,结果才会显示出来。这可能是一个问题,例如在聊天应用程序中,如果用户单击发送按钮后没有立即看到他们的消息。他们将继续单击按钮并多次发送消息:/

为了在使用Optimisic UI和“订阅”时对抗欺骗,两种策略包括:

  1. 检查客户是否有欺诈行为:

    updateupdateQuery函数中:

    // 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 => {});
    
    Run Code Online (Sandbox Code Playgroud)

    而且里面updateQuery在您的订阅:

    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],
          },
        });
      },
    
    Run Code Online (Sandbox Code Playgroud)
  2. 或者,您可以限制在服务器上的订阅,以使其不向新频道的创建者发出。