4

带有订阅的 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 对订阅有意义吗?

4

1 回答 1

7

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

订阅只会在服务器突变解决后才会发出,所以本质上是在服务器响应时。

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

为了在使用 Optimisic UI 和订阅时打击骗子,两种策略包括:

  1. 检查客户端上的欺骗:

    updateandupdateQuery函数中:

    // 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. 或者,您可以限制您在服务器上的订阅,使其不发送给新频道的创建者。

于 2017-05-23T01:40:38.553 回答