Abort Fetch API Requests using AbortController

Поділитися
Вставка
  • Опубліковано 11 жов 2023
  • Learn how to use the AbortController in JavaScript to cancel API requests using fetch in React.
    We'll walk through how to set up the AbortController with a fetch request and use it to cancel and abort stale requests to avoid updating the UI with old data in React.
    🧰 Resources
    Starter: github.com/colbyfayock/demo-s...
    Code: github.com/colbyfayock/my-abo...
    📺 UA-cam: ua-cam.com/users/colbyfayock?sub_c...
    🐦 Twitter: / colbyfayock
    📹 Twitch: / colbyfayock
    ✉️ Newsletter: www.colbyfayock.com/newsletter/
    🎥 What I Use: www.colbyfayock.com/uses
    #colbyfayock #reactjs #api #webdevelopment
  • Наука та технологія

КОМЕНТАРІ • 42

  • @WrestlingTournamentsDotCom
    @WrestlingTournamentsDotCom 4 місяці тому +4

    Finally! Someone demonstrated how to do it outside of a useEffect. This was so difficult to find, great tutorial. Thank you!

  • @RefuelTheRocket
    @RefuelTheRocket 8 місяців тому +1

    Thank you colleague, you really helped me, i spend a day trying to understand, how it works, and with ur video i finally done it!

    • @colbyfayock
      @colbyfayock  8 місяців тому

      You're welcome. Glad it helped

  • @user-dk3fz7tk2n
    @user-dk3fz7tk2n 5 місяців тому

    Love your style in how you explain. Neat, clear. Subscribed.

  • @colbyfayock
    @colbyfayock  8 місяців тому

    Dig deeper into React with my course Full Stack React with Appwrite: spacejelly.dev/reactappwrite
    Otherwise get fresh tutorials and other free content straight to your inbox! colbyfayock.com/news

  • @bandekhoda7801
    @bandekhoda7801 4 місяці тому

    Very useful!
    Previously I didn't know how to implement an AbortController in a handler function because of the reasons you listed, so I always just defaulted to using useEffect with the cleanup function being controller.abort LOL

  • @user-sb3sy6pr5i
    @user-sb3sy6pr5i 3 місяці тому

    very well explained you just earned a sub

  • @rigbyb
    @rigbyb 6 місяців тому

    Thanks, helped me understand it :)

  • @sincethatmoment
    @sincethatmoment 8 місяців тому +2

    Great demonstration Colby, as always. The example project is on spot in terms of illustrating the issue and the solution.
    I have one question. As I understood, the AbortController cancels requests that are initiated but have not been completed yet. So, let's assume fetch returns responses pretty quickly in my connection. Does this mean that I have to type letters quickly for abortcontroller to cancel? And if I type slowly all the previous letters are going to get through. I know you mentioned throttling and stuff at the end, that's probably the solution. I was just wondering about AbortController

    • @colbyfayock
      @colbyfayock  8 місяців тому

      yeah - that's absolutely right. if there's no active request, we can't really cancel it. that's why i had to add the setTimeout inside of the API endpoint because it was too fast, though you could use the Network Tab throttling to potentially see this effect too when testing

  • @Elator11777
    @Elator11777 Місяць тому

    This looks nice, however, in a real production envirionment, you'd never have a search function inside of your component, what if it is imported from utils? How do you handle the abort requests in it? Can you pass refs to an imported function?

  • @antoninogargiulo2308
    @antoninogargiulo2308 Місяць тому

    Great video! What if I have an error boundary (Next.js), and I don't want it to be triggered by cancelled request? Should I check the type of the error catched in the catch block?

    • @colbyfayock
      @colbyfayock  Місяць тому

      did the cancelled request trigger the error boundary? i dont remember having that issue in my code wrapped in a try/catch: github.com/colbyfayock/my-abort-requests/blob/main/src/components/Search/Search.tsx
      perhaps if you show me the code i can get a better idea to try to reproduce and see

  • @irfansaeedkhan7242
    @irfansaeedkhan7242 8 місяців тому

    wow , thanks man, i was searching for something same but when user clicks multiple links to different pages, i want it to abort all others and just focus on the last one,
    also if person is fetching multiple apis data it should about all and only fetch the last one in react/nextjs app, i am unable to do that or simply logic how to do it in whole application at globa,l level

    • @colbyfayock
      @colbyfayock  8 місяців тому

      glad it helped! for doing something globally you would need to be making all requests through some kind of single queue that's accessible globally

  • @Shawn-Mosher
    @Shawn-Mosher 8 місяців тому

    Couldn’t you use debounce so it’s only fired once when the user stops typing?

    • @colbyfayock
      @colbyfayock  8 місяців тому +1

      totally! i mention that in there. or maybe i mentioned throttle as opposed to denounce, but generally, yeah. being able to combine the two would likely be the best bet between having a responsive enough UI and still managing the async requests getting fired out

  • @JavascriptForEverything
    @JavascriptForEverything 5 місяців тому

    nice one

  • @sankaranarayanankm7049
    @sankaranarayanankm7049 Місяць тому

    which is better cleanup of useEffect or abort controller??

    • @colbyfayock
      @colbyfayock  Місяць тому

      hey im not totally following your question - but i believe aborting in a useEffect cleanup function would be a good pattern to prevent the request from continuing

  • @devT44
    @devT44 3 місяці тому

    The error we're getting here is same as CancelledError in axios?

    • @colbyfayock
      @colbyfayock  3 місяці тому

      unfamiliar with axios's handling

  • @divinityinversace
    @divinityinversace 5 днів тому

    does the request get cancelled even if the component is unmounted?

    • @colbyfayock
      @colbyfayock  5 днів тому

      thats a good question and im not 100% sure unless i would test it. i would expect given the initial code had executed with the controller that it would still be cancelled IF the code to cancel it was executed, however if it unmounts and it hadnt run yet, then i would expect it not. if you add the return function to useEffect, you can trigger the cancellation on unmount

    • @divinityinversace
      @divinityinversace 3 дні тому

      @@colbyfayock thanks, i ended up setting up a cleanup function which takes care of the controller stuff

  • @terryellis333
    @terryellis333 6 місяців тому

    Does this work for cancelling put reqeusts also, or just fetch? I'm having difficulty getitng it to cancel a PUT

    • @colbyfayock
      @colbyfayock  6 місяців тому +1

      seemed to work for me! d.pr/i/hDNmgf
      i tested by simply updating my test API route to PUT: github.com/colbyfayock/my-abort-requests/blob/main/src/app/api/search/route.ts#L5
      and the method on the fetch: github.com/colbyfayock/my-abort-requests/blob/main/src/components/Search/Search.tsx#L35

    • @terryellis333
      @terryellis333 6 місяців тому

      @@colbyfayock Ok thanks; yea trying to figure out why this controller.abort isn't actually cancelling anything for me.

    • @colbyfayock
      @colbyfayock  6 місяців тому

      @@terryellis333is it possible the request is completing before it has a chance to cancel? on my local machine i had to add a timeout for testing purposes

    • @terryellis333
      @terryellis333 6 місяців тому

      @@colbyfayock Well what's happening is, our web app is doing puts after every field of a form (no submit button :( ) and they're stacking up... and of course we have a race condition. I followed your example and set up an abort controller using a ref; then we're doing an await on a call that does an axios put to store the data and I'm passing in the abort controller to set the signal. I was expecting the first call to get cancelled, instead both complete with a 200 :(

    • @colbyfayock
      @colbyfayock  6 місяців тому +1

      @@terryellis333got it okay, im not familiar with how this works with Axios, potentially an issue there? but you might have some luck additionally adding throttling on the requests, to prevent the requests from occurring in the first place. that way you're avoiding sending too many requests, but if requests do trigger too quickly still due to differing factors, you have the abortcontroller to manage the cancellation

  • @akylbekrysbekov
    @akylbekrysbekov 4 місяці тому

    but i think we can solve this problem with debounce

    • @colbyfayock
      @colbyfayock  4 місяці тому +1

      I think I mention this in the video but the right solution would be to have both for the use case

  • @ken2ker495
    @ken2ker495 2 місяці тому

    can you give me the api of pixar movie , please ? :>

    • @colbyfayock
      @colbyfayock  2 місяці тому

      hey unfortunately it's not a public API, its just an endpoint that i made that searches a static JSON file. you can find that code here and spin it up though!
      github.com/colbyfayock/my-abort-requests/blob/main/src/app/api/search/route.ts