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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

라이브 토크 나 수업 중에 대화식 애니메이션을 표시해야한다면 슬라이드와 상호 작용하기가 항상 쉽지 않다는 것을 알 수 있습니다.

Astro를 사용하면 빌드 중에 대부분의 사이트를 생성 할 수 있지만 Fuse.js와 같은 것을 사용하여 검색 기능을 처리 할 수있는 작은 서버 측 코드가 있습니다. 이 데모에서는 퓨즈를 사용하여 개인 "북마크"세트를 검색합니다.

문서가 저장되는 동안 Google 문서에서 볼 수있는 것과 유사한 프로젝트 중 하나에서 알림 메시지를 구현하고 싶었습니다. 다시 말해, a

몇 달 전에 나는 해커 뉴스를 썼고 (하나와 마찬가지로) IF 문을 사용하지 않는 것에 대한 (현재 삭제 된) 기사를 가로 질러 달렸습니다. 이 아이디어를 처음 접한다면 (나처럼

공상 과학 소설의 초기부터 우리는 우리와 대화하는 기계에 대해 환상을 가지고 있습니다. 오늘은 평범합니다. 그럼에도 불구하고 제작 기술

Gutenberg가 핵심으로 풀려 났을 때를 기억합니다. 왜냐하면 나는 그날 WordCamp에 있었기 때문입니다. 지금은 몇 달이 지났으므로 점점 더 많은 것을 상상합니다.

대부분의 웹 애플리케이션의 배후에있는 아이디어는 데이터베이스에서 데이터를 가져 와서 최상의 방법으로 사용자에게 제시하는 것입니다. 우리가 거기에서 데이터를 다룰 때

#039;는 당신이 의미있는 것처럼 보일 수있는 상황에 대한 약간의 단계를 수행하자. 이것에서


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.
