[React] Optimistic UI update in React using setState()

In this lesson we will refactor an existing UI update from a typical loading approach to an optimistic UI updateapproach to give our users a faster, more snappy experience. Instead of displaying a "loading" UI to our users while our request is in progress, we will immediately update the UI and account for reverting state and displaying an error in the event of a failure. We can accomplish this relatively easily in React, thanks to the simplicity and power of setState() combined with making use of Javascript's lexical scoping and closures.

 

class App extends React.Component {
  // ...

  deleteItemOptimistic = id => {
    // 1) Snapshot target item so we can restore it in the case of failure
    const deletingItem = this.state.items.find(item => item.id === id);

    // 2) Assume success. Immediately update state
    this.setState(state => ({
      items: state.items.filter(item => item.id !== id),
    }));

    // 3) If the request failed revert state and display error.
    deleteItemRequest(id).catch(() =>
      this.setState(state => ({
        // Restore the single, deleted item.
        // Use sort to ensure it is inserted where expected.
        items: [...state.items, deletingItem].sort((a, b) => a.id - b.id),
        error: `Request failed for item ${id}`,
      }))
    );
  };

  // ...
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值