Это видео недоступно.
Сожалеем об этом.

JavaScript Fetch API - One Mistake I ALWAYS MAKE!

Поделиться
HTML-код
  • Опубликовано: 4 окт 2023
  • Don't make this mistake using JavaScript fetch!
    The fetch API only throws an error if you the response is a 500 status. Otherwise, it doesn't throw an error. This means it's your responsibility to ensure the response has come back successfully with a status of 200. It's your responsibility to handle any other type of status like a 404.
    *DISCORD*
    Join the Learn Build Teach Discord Server 💬 - / discord
    *STAY IN TOUCH 👋*
    Newsletter 🗞 - www.jamesqquick.com/newsletter
    Follow me on Twitter 🐦 - / jamesqquick
    Check out the Podcast - compressed.fm/
    Courses - jamesqquick.com/courses
    *QUESTIONS ABOUT MY SETUP*
    Check out my Uses page for my VS Code setup, what recording equipment I use, etc. www.jamesqquick.com/uses

Комментарии • 97

  • @Ghandmann1
    @Ghandmann1 10 месяцев назад +40

    Minor correction: Fetch only throws on network error (can't connect, connection interrupted, DNS failed, etc.) but not on status code 500. Every valid http request-response cycle is just that: valid for fetch. The interpretation of the status code is left to the developer.

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +7

      Ahhh great point! Thanks for clarifying that!!

    • @fennecbesixdouze1794
      @fennecbesixdouze1794 10 месяцев назад +7

      This isn't a minor correction.

  • @DavidWoodMusic
    @DavidWoodMusic 10 месяцев назад +20

    I work for a banking firm and we have built so many custom tools and wrappers around literally everything that sometimes I forget how these APIs work in their base form.
    Appreciate you James.

  • @MentorAliu
    @MentorAliu 10 месяцев назад +20

    i like to throw error with status code if(!response.ok) and then in the next if statement check if the response is json, because sometimes you receive templates and you want to handle that as well, if everything else goes right i return the json

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +1

      That's a great option! Thanks for sharing that!

    • @JamesLaenNeal
      @JamesLaenNeal 10 месяцев назад +2

      Yeah, I think this is the "correct" way to do it. Though less common, there are other HTTP statuses that may accompany a still-successful request.

    • @wilofgren
      @wilofgren 10 месяцев назад

      I try to route all my requests through a single service and run my response through a handle error function that returns an alert with the error status code and status text.

    • @MentorAliu
      @MentorAliu 10 месяцев назад

      @@JamesLaenNeal yep, best approach is to discuss with the backend about specifics, usually each team requires different ways to handle the status codes, it's not jack of all trades, also libraries require specifically to throw errors so they can catch it in the view and manipulate the view according to the error, (example show a popup if a post request failed), TanstackQuery one of the libraries

  • @billygnosis
    @billygnosis 10 месяцев назад +17

    The `Response` interface has a property that allows you to check whether or not the response was successful (200-299). So you can just write: `if (!response.ok) { ... }`

  • @davorinrusevljan6440
    @davorinrusevljan6440 10 месяцев назад +5

    I did that mistake quite a few times. There is res.ok property that can be checked. If not true I usually throw an error

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      Ah that's a nice one as well!

  • @ebrahimmehri
    @ebrahimmehri Месяц назад

    Excellent! I'm a professional RUclips uploader myself and I'm quite aware how difficult it is to make a single video. Bravo! Keep up the good work.

  • @neontuts5637
    @neontuts5637 10 месяцев назад +1

    Thanks for sharing James. I thought the catch() method catches all types of errors.

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +2

      I always assume the same thing lol Fetch doesn't consider other statuses except 5xx to be errors

  • @nopainnogame9897
    @nopainnogame9897 Месяц назад

    if I check
    if (!response.ok) {}
    is it not the same?

  • @juanmacias5922
    @juanmacias5922 10 месяцев назад

    That makes sense, we should be checking the status code!

  • @ThanHtutZaw3
    @ThanHtutZaw3 10 месяцев назад

    Quick Question: How can I show fcm notification in foreground instead of toast or new Notification() without action button support.

  • @yayuyo7188
    @yayuyo7188 10 месяцев назад +1

    In this video, the console.log output is displayed right next to the source code.
    Is this a vscode extension? It looks very useful!

    • @ongke3655
      @ongke3655 10 месяцев назад +1

      it's quokka

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +1

      Yeah its the quokka extension. It's so good!!

    • @yayuyo7188
      @yayuyo7188 10 месяцев назад

      Thx bro!

  • @ondrejhavazik4124
    @ondrejhavazik4124 10 месяцев назад

    Very helpfull video James! I also thought, that 4xx is error which should be catch :-D. Can I ask you, I assume you are using quokka and you have to use 'node-fetch' library for create API requests, this library is installed globally or somewhere in your project? Thanks! :-)

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      Yep, using Quokka. With Quokka it gives me the ability to install packages for a given file. I think that's with the paid tier though. It may not be available on free tier. Try it out and let me know!

  • @Stoney_Eagle
    @Stoney_Eagle 10 месяцев назад +4

    I'll keep using axios 😂 still gets the job done very well.

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +1

      haha whatever works

    • @lucneville7925
      @lucneville7925 10 месяцев назад +1

      Us too using an interceptor to handle error status codes, makes for a lot cleaner code

  • @kovoliver
    @kovoliver 5 месяцев назад

    I think the proper approach is, when you develop a JSON REST API, you must send the body always in JSON format, including when the status is 4xx or 5xx. So the basic error is in the API implementation, but of course, you have to deal with this in the case of some APIs.

  • @Okir09
    @Okir09 10 месяцев назад

    Hi James, noob question but how do you get directly your console.log in the IDE next to it? : O thanks

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +1

      It's the Quokka extension. really cool. Highly recommend it :)

    • @Okir09
      @Okir09 10 месяцев назад

      @@JamesQQuick thank you!

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      You're very welcome! That's what i'm here for!@@Okir09

  • @jordan4220
    @jordan4220 10 месяцев назад

    Probably should also check if the content type is application/JSON.. we once had an nginx proxied rest API throw from nginx because the upload payload was too large and it returned an html error page which the UI code gladly tried to parse as JSON 😅

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      Ah yes another great callout!

  • @swildermuth
    @swildermuth 10 месяцев назад

    Great video!

  • @j4nch
    @j4nch 10 месяцев назад

    I'm not sure to get the point, if in both case(40x and 50x) we get an error in either the fetch or the json. In either case, I would log an error with all the info I could have(url and status) and provide some error status after.

    • @jimothyus
      @jimothyus 10 месяцев назад

      What if the server responds with a status 400 and returns valid json telling you what you did wrong in the request? Fetch wont throw and neither will json parse. Point is you have to look at every api specifically.

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      Yeah the overall point is you have to inspect the response appropriately to ensure it's doing what you expect

  • @bigbadcatbigbcy2933
    @bigbadcatbigbcy2933 6 месяцев назад

    good to know

  • @AlThePal78
    @AlThePal78 10 месяцев назад

    Great video

  • @AlThePal78
    @AlThePal78 10 месяцев назад

    Could you make a status switch statement

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +1

      Absolutely you could!

    • @AlThePal78
      @AlThePal78 5 месяцев назад

      why do you have import here? Is it because it is a REACT.js fetch?

  • @braveitor
    @braveitor 10 месяцев назад

    which extension is that that shows json response within vscode?

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +1

      It's the Quokka extension! It's awesome :)

    • @braveitor
      @braveitor 10 месяцев назад

      @@JamesQQuick Thanks!! It seems really useful! I'm installing that right now. Good job and thanks for all your videos. Very informative and interesting.

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      Yeahhh! Let me know what you think :)@@braveitor

  • @CodeWithHarshu
    @CodeWithHarshu 10 месяцев назад

    How you calling the await method without the async function

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      Latest versions of node allow you to run top level await :)

    • @cranberry888
      @cranberry888 10 месяцев назад

      ​@@JamesQQuickdidn't know that wow!! so many new information, james thanks a lot!

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      Yeah! Happy to help :)@@cranberry888

  • @harshvardhanthakur4688
    @harshvardhanthakur4688 29 дней назад

    hey its helps me

  • @thecoderguy_0001
    @thecoderguy_0001 10 месяцев назад

    whats that quokka thing in the terminal?

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +1

      It's an extension that live reloads your code. It's really awesome!

    • @thecoderguy_0001
      @thecoderguy_0001 10 месяцев назад

      @@JamesQQuick oh will try it

  • @ifeanyinnaemego
    @ifeanyinnaemego 10 месяцев назад

    Nice one

  • @blackpurple9163
    @blackpurple9163 10 месяцев назад

    Should the catch block catch all errors in fetch? Why hasn't that been the case yet if fetch has been here for so long already

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +1

      Catch block while catch all errors, yes. The point is that Fetch doesn't consider most things to actually be an error.

    • @blackpurple9163
      @blackpurple9163 10 месяцев назад

      @@JamesQQuick ooh, so it's the fetch that's the problem here, have they not fixed it yet or is fetch fundamentally different?
      Because I heard in many videos that fetch will always return a response in it's promise, it won't throw direct error, is this what they were referring to?

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +1

      That's mostly true. As @ghandmann1 said below, "Fetch only throws on network error (can't connect, connection interrupted, DNS failed, etc.) but not on status code 500. Every valid http request-response cycle is just that: valid for fetch" @@blackpurple9163

    • @blackpurple9163
      @blackpurple9163 10 месяцев назад

      @@JamesQQuick so your implementation will catch most of the errors right?
      I'm new and was taught to use axios, but fetch is how I learnt promises and async-await so fetch is what I prefer, and less libraries I ship the better I think my end product will be

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +1

      Using try/catch means all errors will get caught from any code that runs inside of the try block. You just have to manually inspect the response from the fetch request to make sure it returned the status you expect.@@blackpurple9163

  • @alexanderkomanov4151
    @alexanderkomanov4151 10 месяцев назад

    Great!

  • @kabal911
    @kabal911 10 месяцев назад

    This kind of annoyed me coming from axios. But then I realized that’s fetch’s api is actually much nicer.
    It assumes that if it gets a server response, its job was successful.
    Who’s to say you aren’t calling some wacky API where 500 is an acceptable and expected status code
    And I don’t want libraries choosing to throw exceptions for non exceptional things
    If I give it an endpoint that it is unable to connect to, then I am fine with the exception being thrown for me

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      Yeah axios is great also. Just depends on what you need to do with the response.

  • @BoZZstuDIOSin1981
    @BoZZstuDIOSin1981 10 месяцев назад

    thx.

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      You're very welcome! Have you made that mistake before?

  • @0x007A
    @0x007A 10 месяцев назад +1

    Not checking the status of an API request is pure amateur or hubris of the part of the programmer. Catching the error as early as possible saves countless hours of debugging.

  • @VivekYadav-up7uu
    @VivekYadav-up7uu 10 месяцев назад

    Nice

  • @vatmanzlokuz680
    @vatmanzlokuz680 26 дней назад

    wtf,who deserialize a request without check status code xd

  • @taquanminhlong
    @taquanminhlong 10 месяцев назад

    for me, i'll just make my api return json {error: "Not found"} with status 404 then it's fine to do await res.json() from js 😂

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      haha yeah that works if the API is built that way. Depends on the API

  • @walnutsandbeastiality866
    @walnutsandbeastiality866 10 месяцев назад

    Mistake...? 🤔💭
    ,,Into the flood again
    Same old trip it was back then
    *So I made a big mistaaaaaake*
    Try to see it once my way!" 🎶
    (Alice in Chains)

  • @omega.developer
    @omega.developer 10 месяцев назад

    🎉

  • @Serpsss
    @Serpsss 10 месяцев назад

    A tiny correction: developerasaurus isn't a valid pokemon... yet. Give it time, Nintendo have already started scraping the bottom of the barrel that's why I try to ignore anything post Hoenn 😂 (gba).

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +1

      haha one day I'd love to see developerasaurus become a real pokemon :)

  • @GildwareTechnologies
    @GildwareTechnologies 10 месяцев назад

    The JavaScript Fetch API is a modern and powerful built-in feature that allows you to make network requests (e.g., HTTP requests) from a web page or application. It provides a more flexible and promise-based alternative to the older XMLHttpRequest (XHR) API for making asynchronous requests to servers and fetching data from external resources like APIs, databases, or other websites.
    Here are some key features and concepts related to the JavaScript Fetch API:
    1. **Promises:** The Fetch API is based on Promises, which provide a way to handle asynchronous operations more elegantly and avoid callback hell. Promises allow you to write cleaner and more maintainable code for handling responses.
    2. **HTTP Methods:** Fetch supports various HTTP methods, including GET, POST, PUT, DELETE, and more. These methods determine the type of request you want to make to a server.
    3. **Headers:** You can specify custom headers in your Fetch requests, which is important when working with APIs that require authentication or expect specific headers.
    4. **Request and Response Objects:** The Fetch API uses Request and Response objects to represent the request being sent and the response received. You can customize request parameters and handle response data using these objects.
    5. **JSON Parsing:** Fetch makes it easy to work with JSON data, which is commonly used in modern web applications. You can use the `.json()` method on a response object to parse JSON data from the response.
    6. **Error Handling:** Fetch allows you to handle network errors and HTTP errors (e.g., 404 or 500) gracefully, providing better error handling capabilities compared to traditional XHR.
    Here's a basic example of how to use the Fetch API to make a GET request:
    ```javascript
    fetch('api.example.com/data')
    .then(response => {
    if (!response.ok) {
    throw new Error('Network response was not ok');
    }
    return response.json(); // Parse JSON data from the response
    })
    .then(data => {
    console.log(data); // Process the fetched data
    })
    .catch(error => {
    console.error('Fetch error:', error);
    });
    ```
    In this example, we fetch data from the `api.example.com/data` URL, check if the response is successful (status code 200), parse the JSON data, and handle any errors that may occur during the request.
    The Fetch API simplifies many common tasks associated with making network requests in JavaScript, making it a preferred choice for modern web development.
    If you're interested in scholarships, you can explore opportunities like the one available at www.gildware.com/scholarship to support your education and career in web development, which may include working with the Fetch API for data retrieval.

    • @AngeloTadeucci
      @AngeloTadeucci 10 месяцев назад

      wtf is this chatgpt type of response lol

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      bahahah feels like it!

  • @liu-river
    @liu-river 10 месяцев назад

    Can't trust APIs to give you the right status code, what if guy who designed API decided to return you null or undefined, then there is no error. Best to read API doc so you know what to expect. This is a stupid JS design, it's not an error first language, instead we got to work with stupid try catch.

  • @kevinzunigacuellar
    @kevinzunigacuellar 10 месяцев назад

    I made this error yesterday, stole about 30 minutes of my life 😿

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад

      hahah glad to know I'm not the only one

  • @mario_luis_dev
    @mario_luis_dev 10 месяцев назад

    don't you get around all this by using the old `promise.then()` api? I still don't get why ppl are so crazy about the async-await syntax... it doesn't seem to do anything better than `promise.then()`

    • @0x007A
      @0x007A 10 месяцев назад +1

      async-await is cleaner - while both accomplish the same outcome it is easier to read and reason about than a promise potentially followed by a chain of then clauses. However, knowing how and when to use both methods is preferable. You never know when you might have to read someone's source code.

    • @mario_luis_dev
      @mario_luis_dev 10 месяцев назад

      @@0x007A that's the thing...I keep hearing everyone repeating that it's "cleaner", but to me it doesn't really look that way. I much rather see `promise.then().catch()` than async-await wrapped in try-catch clauses. the latter doesn't look cleaner in any way to me.

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +2

      Cleaner is relative. I certainly think it's cleaner, but that's just my opinion. Regardless, you'd have the same issue if you used then/catch. You'd still have to check the response status before trying to parse JSON safely

    • @mario_luis_dev
      @mario_luis_dev 10 месяцев назад +2

      @@JamesQQuick definitely subjective, that’s why I’ve kept saying “to me”. Those chained promise methods to me look much cleaner than the equivalent code wrapped in try-catch, if-else clauses… Looks more declarative.

    • @JamesQQuick
      @JamesQQuick  10 месяцев назад +1

      Fair enough! Whatever works for you. To your original quesiton though, you don't get around having to check statuses when you're using then/catch. Similar logic has to be applied@@mario_luis_dev