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: …


The post How to Cancel Pending API Requests to Show Correct Data appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.


This content originally appeared on CSS-Tricks and was authored by Georgi Nikoloff

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 <App /> 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.


The post How to Cancel Pending API Requests to Show Correct Data appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.


This content originally appeared on CSS-Tricks and was authored by Georgi Nikoloff


Print Share Comment Cite Upload Translate Updates
APA

Georgi Nikoloff | Sciencx (2021-06-25T14:33:33+00:00) How to Cancel Pending API Requests to Show Correct Data. Retrieved from https://www.scien.cx/2021/06/25/how-to-cancel-pending-api-requests-to-show-correct-data/

MLA
" » How to Cancel Pending API Requests to Show Correct Data." Georgi Nikoloff | Sciencx - Friday June 25, 2021, https://www.scien.cx/2021/06/25/how-to-cancel-pending-api-requests-to-show-correct-data/
HARVARD
Georgi Nikoloff | Sciencx Friday June 25, 2021 » How to Cancel Pending API Requests to Show Correct Data., viewed ,<https://www.scien.cx/2021/06/25/how-to-cancel-pending-api-requests-to-show-correct-data/>
VANCOUVER
Georgi Nikoloff | Sciencx - » How to Cancel Pending API Requests to Show Correct Data. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/25/how-to-cancel-pending-api-requests-to-show-correct-data/
CHICAGO
" » How to Cancel Pending API Requests to Show Correct Data." Georgi Nikoloff | Sciencx - Accessed . https://www.scien.cx/2021/06/25/how-to-cancel-pending-api-requests-to-show-correct-data/
IEEE
" » How to Cancel Pending API Requests to Show Correct Data." Georgi Nikoloff | Sciencx [Online]. Available: https://www.scien.cx/2021/06/25/how-to-cancel-pending-api-requests-to-show-correct-data/. [Accessed: ]
rf:citation
» How to Cancel Pending API Requests to Show Correct Data | Georgi Nikoloff | Sciencx | https://www.scien.cx/2021/06/25/how-to-cancel-pending-api-requests-to-show-correct-data/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.