搜索
首页web前端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中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
@rules具有多少特异性,例如@keyframes和@media?@rules具有多少特异性,例如@keyframes和@media?Apr 18, 2025 am 11:34 AM

前几天我得到了这个问题。我的第一个想法是:奇怪的问题!特异性是关于选择者的,而在符号不是选择器,那么...无关紧要?

您可以嵌套@Media和@support查询吗?您可以嵌套@Media和@support查询吗?Apr 18, 2025 am 11:32 AM

是的,您可以,而且它并不重要。不需要CSS预处理器。它在常规CSS中起作用。

快速吞噬缓存破坏快速吞噬缓存破坏Apr 18, 2025 am 11:23 AM

您应该肯定会在CSS和JavaScript(以及图像和字体以及其他内容)等资产上设置遥远的高速缓存标头。告诉浏览器

寻找可以监视CSS质量和复杂性的堆栈寻找可以监视CSS质量和复杂性的堆栈Apr 18, 2025 am 11:22 AM

许多开发人员写了如何维护CSS代码库的文章,但并没有很多关于如何测量该代码库质量的文章。当然,我们有

数据学家用于建议不执行值的值数据学家用于建议不执行值的值Apr 18, 2025 am 11:08 AM

您是否曾经有一种需要接受简短而任意的文本的表格?喜欢名字或其他。那完全是用的。有很多

苏黎世的最初会议苏黎世的最初会议Apr 18, 2025 am 11:03 AM

我很高兴能前往瑞士苏黎世参加前界(Love the Name and URL!)。我以前从未去过瑞士,所以我很兴奋

使用CloudFlare工人建立全栈无服务器应用程序使用CloudFlare工人建立全栈无服务器应用程序Apr 18, 2025 am 10:58 AM

我在软件开发方面最喜欢的发展之一是无服务器的出现。作为一个倾向于陷入细节的开发人员

在NUXT应用程序中创建动态路由在NUXT应用程序中创建动态路由Apr 18, 2025 am 10:53 AM

在这篇文章中,我们将使用我构建和部署的电子商务商店演示来进行Netlify,以展示如何为传入数据制作动态路线。这是一个公平的

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 个月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
1 个月前By尊渡假赌尊渡假赌尊渡假赌
威尔R.E.P.O.有交叉游戏吗?
1 个月前By尊渡假赌尊渡假赌尊渡假赌

热工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器