正しいデータを表示するために保留中のAPIリクエストをキャンセルする方法
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:
- It creates a new cached variable, abortController, in a useRef in the
component. - For each new fetch, it initializes that fetch with a new AbortController and obtains its corresponding AbortSignal.
- It passes the obtained AbortSignal to the fetch() call.
- 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 サイトの他の関連記事を参照してください。

ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

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

ホットトピック











それは' Vueチームにそれを成し遂げてくれておめでとうございます。それは大規模な努力であり、長い時間がかかったことを知っています。すべての新しいドキュメントも同様です。

最近のビットコインの価格が20k $ $ USDを超えており、最近30Kを破ったので、イーサリアムを作成するために深く掘り下げる価値があると思いました

私はこの非常に正当な質問で誰かに書いてもらいました。 Leaは、ブラウザから有効なCSSプロパティ自体を取得する方法についてブログを書いています。それはこのようなものです。

先日、Corey Ginnivanのウェブサイトから、この特に素敵なビットを見つけました。そこでは、スクロール中にカードのコレクションが互いに積み重ねられていました。

これらのデスクトップアプリがいくつかあり、目標があなたのサイトをさまざまな次元ですべて同時に表示しています。たとえば、書くことができます

WordPressエディターでユーザーに直接ドキュメントを表示する必要がある場合、それを行うための最良の方法は何ですか?

フレックスレイアウトの紫色のスラッシュ領域に関する質問フレックスレイアウトを使用すると、開発者ツールなどの混乱する現象に遭遇する可能性があります(D ...
