Apollo js 订阅乐观 UI

Apollo js Subscriptions Optimistic UI

Optimistic 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 => {});

它添加了两次相同的项目触发重复键异常。 因此,乐观 ui 对订阅有意义吗?

optimisticResponse 在服务器收到响应之前触发 update。然后当服务器响应时,再次触发 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 => {});
    

    并且也在您订阅的 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],
          },
        });
      },
    
  2. 或者您可以限制您在服务器上的订阅不发送给新频道的创建者。