検索
ホームページウェブフロントエンドCSSチュートリアル正しいデータを表示するために保留中のAPIリクエストをキャンセルする方法

How to Cancel Pending API Requests to Show Correct Data

I recently had to create a widget in React that fetches data from multiple API endpoints. As the user clicks around, new data is fetched and marshalled into the UI. But it caused some problems.

One problem quickly became evident: if the user clicked around fast enough, as previous network requests got resolved, the UI was updated with incorrect, outdated data for a brief period of time.

We can debounce our UI interactions, but that fundamentally does not solve our problem. Outdated network fetches will resolve and update our UI with wrong data up until the final network request finishes and updates our UI with the final correct state. The problem becomes more evident on slower connections. Furthermore, we’re left with useless networks requests that waste the user’s data.

Here is an example I built to illustrate the problem. It grabs game deals from Steam via the cool Cheap Shark API using the modern fetch() method. Try rapidly updating the price limit and you will see how the UI flashes with wrong data until it finally settles.

The solution

Turns out there is a way to abort pending DOM asynchronous requests using an AbortController. You can use it to cancel not only HTTP requests, but event listeners as well.

The AbortController interface represents a controller object that allows you to abort one or more Web requests as and when desired.

—Mozilla Developer Network

The AbortController API is simple: it exposes an AbortSignal that we insert into our fetch() calls, like so:

const abortController = new AbortController()
const signal = abortController.signal
fetch(url, { signal })

From here on, we can call abortController.abort() to make sure our pending fetch is aborted.

Let’s rewrite our example to make sure we are canceling any pending fetches and marshalling only the latest data received from the API into our app:

The code is mostly the same with few key distinctions:

  1. It creates a new cached variable, abortController, in a useRef in the component.
  2. For each new fetch, it initializes that fetch with a new AbortController and obtains its corresponding AbortSignal.
  3. It passes the obtained AbortSignal to the fetch() call.
  4. It aborts itself on the next fetch.
const App = () => {
 // Same as before, local variable and state declaration
 // ...

 // Create a new cached variable abortController in a useRef() hook
 const abortController = React.useRef()

 React.useEffect(() => {
  // If there is a pending fetch request with associated AbortController, abort
  if (abortController.current) {
    abortController.abort()
  }
  // Assign a new AbortController for the latest fetch to our useRef variable
  abortController.current = new AbortController()
  const { signal } = abortController.current

  // Same as before
  fetch(url, { signal }).then(res => {
    // Rest of our fetching logic, same as before
  })
 }, [
  abortController,
  sortByString,
  upperPrice,
  lowerPrice,
 ])
}

Conclusion

That’s it! We now have the best of both worlds: we debounce our UI interactions and we manually cancel outdated pending network fetches. This way, we are sure that our UI is updated once and only with the latest data from our API.

以上が正しいデータを表示するために保留中のAPIリクエストをキャンセルする方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
マウスの動きのシミュレーションマウスの動きのシミュレーションApr 22, 2025 am 11:45 AM

ライブトークやクラス中にインタラクティブなアニメーションを表示しなければならなかった場合、スライドと対話するのが必ずしも簡単ではないことを知っているかもしれません

Astro ActionsとFuse.jsでのパワー検索Astro ActionsとFuse.jsでのパワー検索Apr 22, 2025 am 11:41 AM

Astroを使用すると、ビルド中にほとんどのサイトを生成できますが、fuse.jsのようなものを使用して検索機能を処理できるサーバー側のコードが少しあります。このデモでは、ヒューズを使用して、個人の「ブックマーク」セットを検索します。

未定義:3番目のブール値未定義:3番目のブール値Apr 22, 2025 am 11:38 AM

ドキュメントが保存されている間にGoogleドキュメントに表示されるものと同様に、プロジェクトの1つに通知メッセージを実装したかったのです。言い換えれば、a

三元声明の防衛三元声明の防衛Apr 22, 2025 am 11:25 AM

数ヶ月前、私はハッカーのニュースに出演していました(1つのように)。あなたがこのアイデアに慣れていない場合(私のように

多言語翻訳にWeb Speech APIを使用します多言語翻訳にWeb Speech APIを使用しますApr 22, 2025 am 11:23 AM

サイエンスフィクションの初期の頃から、私たちは私たちに話しかける機械について空想してきました。今日は当たり前です。それでも、作成のための技術

Jetpack GutenbergブロックJetpack GutenbergブロックApr 22, 2025 am 11:20 AM

私はその日私たちにワードキャンプにいたので、グーテンバーグがコアにリリースされたときのことを覚えています。数ヶ月が今から経過しているので、ますます私たちのことを想像してください

VUEで再利用可能なページネーションコンポーネントを作成しますVUEで再利用可能なページネーションコンポーネントを作成しますApr 22, 2025 am 11:17 AM

ほとんどのWebアプリケーションの背後にあるアイデアは、データベースからデータを取得し、可能な限り最良の方法でユーザーに提示することです。そこでデータを扱うとき

「ボックスシャドウ」とクリップパスを一緒に使用します「ボックスシャドウ」とクリップパスを一緒に使用しますApr 22, 2025 am 11:13 AM

'は、理にかなっていると思われることを非常に実行できる状況を少し段階的に実行しますが、CSSのトリックでそれを成し遂げることができます。これで

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。