JavaScript Fetch API - One Mistake I ALWAYS MAKE!

  Рет қаралды 28,672

James Q Quick

James Q Quick

Күн бұрын

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.jamesqquic...
Follow me on Twitter 🐦 - / jamesqquick
Check out the Podcast - compressed.fm/
Courses - jamesqquick.co...
*QUESTIONS ABOUT MY SETUP*
Check out my Uses page for my VS Code setup, what recording equipment I use, etc. www.jamesqquic...

Пікірлер: 98
@Ghandmann1
@Ghandmann1 Жыл бұрын
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 Жыл бұрын
Ahhh great point! Thanks for clarifying that!!
@fennecbesixdouze1794
@fennecbesixdouze1794 11 ай бұрын
This isn't a minor correction.
@ondrejhavazik4124
@ondrejhavazik4124 11 ай бұрын
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 11 ай бұрын
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!
@MentorAliu
@MentorAliu Жыл бұрын
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 Жыл бұрын
That's a great option! Thanks for sharing that!
@JamesLaenNeal
@JamesLaenNeal Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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
@DavidWoodMusic
@DavidWoodMusic Жыл бұрын
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.
@JamesQQuick
@JamesQQuick Жыл бұрын
You're very welcome!
@billygnosis
@billygnosis Жыл бұрын
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) { ... }`
@chadbekmezian4806
@chadbekmezian4806 11 ай бұрын
This is what I always do
@bigbadcatbigbcy2933
@bigbadcatbigbcy2933 8 ай бұрын
oh thanks
@davorinrusevljan6440
@davorinrusevljan6440 Жыл бұрын
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 Жыл бұрын
Ah that's a nice one as well!
@emilemil1
@emilemil1 3 күн бұрын
I would go a step further and also validate the body before parsing it. Sometimes you get a 2xx response but the body is not at all what you expected, sometimes it may even contain an error. I've also used services that sometimes returned redirect status codes (30x) on both success and error so the code was basically useless.
@Stoney_Eagle
@Stoney_Eagle Жыл бұрын
I'll keep using axios 😂 still gets the job done very well.
@JamesQQuick
@JamesQQuick Жыл бұрын
haha whatever works
@lucneville7925
@lucneville7925 11 ай бұрын
Us too using an interceptor to handle error status codes, makes for a lot cleaner code
@0x007A
@0x007A Жыл бұрын
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.
@liu-river
@liu-river 11 ай бұрын
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.
@vatmanzlokuz680
@vatmanzlokuz680 2 ай бұрын
wtf,who deserialize a request without check status code xd
@nopainnogame9897
@nopainnogame9897 3 ай бұрын
if I check if (!response.ok) {} is it not the same?
@ebrahimmehri
@ebrahimmehri 2 ай бұрын
Excellent! I'm a professional KZbin uploader myself and I'm quite aware how difficult it is to make a single video. Bravo! Keep up the good work.
@neontuts5637
@neontuts5637 Жыл бұрын
Thanks for sharing James. I thought the catch() method catches all types of errors.
@JamesQQuick
@JamesQQuick Жыл бұрын
I always assume the same thing lol Fetch doesn't consider other statuses except 5xx to be errors
@yayuyo7188
@yayuyo7188 Жыл бұрын
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 Жыл бұрын
it's quokka
@JamesQQuick
@JamesQQuick Жыл бұрын
Yeah its the quokka extension. It's so good!!
@yayuyo7188
@yayuyo7188 Жыл бұрын
Thx bro!
@kovoliver
@kovoliver 6 ай бұрын
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.
@harshvardhanthakur4688
@harshvardhanthakur4688 2 ай бұрын
hey its helps me
@ThanHtutZaw3
@ThanHtutZaw3 Жыл бұрын
Quick Question: How can I show fcm notification in foreground instead of toast or new Notification() without action button support.
@bigbadcatbigbcy2933
@bigbadcatbigbcy2933 8 ай бұрын
good to know
@jordan4220
@jordan4220 11 ай бұрын
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 11 ай бұрын
Ah yes another great callout!
@Serpsss
@Serpsss Жыл бұрын
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 Жыл бұрын
haha one day I'd love to see developerasaurus become a real pokemon :)
@swildermuth
@swildermuth 11 ай бұрын
Great video!
@taquanminhlong
@taquanminhlong Жыл бұрын
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 Жыл бұрын
haha yeah that works if the API is built that way. Depends on the API
@kabal911
@kabal911 Жыл бұрын
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 Жыл бұрын
Yeah axios is great also. Just depends on what you need to do with the response.
@juanmacias5922
@juanmacias5922 Жыл бұрын
That makes sense, we should be checking the status code!
@kevinzunigacuellar
@kevinzunigacuellar Жыл бұрын
I made this error yesterday, stole about 30 minutes of my life 😿
@JamesQQuick
@JamesQQuick Жыл бұрын
hahah glad to know I'm not the only one
@j4nch
@j4nch Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
Yeah the overall point is you have to inspect the response appropriately to ensure it's doing what you expect
@Okir09
@Okir09 11 ай бұрын
Hi James, noob question but how do you get directly your console.log in the IDE next to it? : O thanks
@JamesQQuick
@JamesQQuick 11 ай бұрын
It's the Quokka extension. really cool. Highly recommend it :)
@Okir09
@Okir09 11 ай бұрын
@@JamesQQuick thank you!
@JamesQQuick
@JamesQQuick 11 ай бұрын
You're very welcome! That's what i'm here for!@@Okir09
@AlThePal78
@AlThePal78 11 ай бұрын
Great video
@alexanderkomanov4151
@alexanderkomanov4151 Жыл бұрын
Great!
@CodeWithHarshu
@CodeWithHarshu Жыл бұрын
How you calling the await method without the async function
@JamesQQuick
@JamesQQuick Жыл бұрын
Latest versions of node allow you to run top level await :)
@cranberry888
@cranberry888 Жыл бұрын
​@@JamesQQuickdidn't know that wow!! so many new information, james thanks a lot!
@JamesQQuick
@JamesQQuick Жыл бұрын
Yeah! Happy to help :)@@cranberry888
@braveitor
@braveitor Жыл бұрын
which extension is that that shows json response within vscode?
@JamesQQuick
@JamesQQuick Жыл бұрын
It's the Quokka extension! It's awesome :)
@braveitor
@braveitor Жыл бұрын
@@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 Жыл бұрын
Yeahhh! Let me know what you think :)@@braveitor
@VivekYadav-up7uu
@VivekYadav-up7uu Жыл бұрын
Nice
@AlThePal78
@AlThePal78 11 ай бұрын
Could you make a status switch statement
@JamesQQuick
@JamesQQuick 11 ай бұрын
Absolutely you could!
@AlThePal78
@AlThePal78 6 ай бұрын
why do you have import here? Is it because it is a REACT.js fetch?
@ifeanyinnaemego
@ifeanyinnaemego Жыл бұрын
Nice one
@thecoderguy_0001
@thecoderguy_0001 Жыл бұрын
whats that quokka thing in the terminal?
@JamesQQuick
@JamesQQuick Жыл бұрын
It's an extension that live reloads your code. It's really awesome!
@thecoderguy_0001
@thecoderguy_0001 Жыл бұрын
@@JamesQQuick oh will try it
@blackpurple9163
@blackpurple9163 Жыл бұрын
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 Жыл бұрын
Catch block while catch all errors, yes. The point is that Fetch doesn't consider most things to actually be an error.
@blackpurple9163
@blackpurple9163 Жыл бұрын
@@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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
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
@omega.developer
@omega.developer Жыл бұрын
🎉
@BoZZstuDIOSin1981
@BoZZstuDIOSin1981 Жыл бұрын
thx.
@JamesQQuick
@JamesQQuick Жыл бұрын
You're very welcome! Have you made that mistake before?
@GildwareTechnologies
@GildwareTechnologies 11 ай бұрын
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 11 ай бұрын
wtf is this chatgpt type of response lol
@JamesQQuick
@JamesQQuick 11 ай бұрын
bahahah feels like it!
@walnutsandbeastiality866
@walnutsandbeastiality866 Жыл бұрын
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)
@mario_luis_dev
@mario_luis_dev Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
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
Abort Fetch API Requests using AbortController
6:37
Colby Fayock
Рет қаралды 10 М.
Brawl Stars Edit😈📕
00:15
Kan Andrey
Рет қаралды 58 МЛН
From Small To Giant Pop Corn #katebrush #funny #shorts
00:17
Kate Brush
Рет қаралды 71 МЛН
Officer Rabbit is so bad. He made Luffy deaf. #funny #supersiblings #comedy
00:18
Funny superhero siblings
Рет қаралды 12 МЛН
Cute
00:16
Oyuncak Avı
Рет қаралды 12 МЛН
Top 5 Async Mistakes for JavaScript Beginners (Don’t make these!)
15:11
The TSConfig Cheat Sheet
5:36
Matt Pocock
Рет қаралды 36 М.
JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue
12:35
5 JavaScript Concepts You HAVE TO KNOW
9:38
James Q Quick
Рет қаралды 1,4 МЛН
5 JavaScript API Key Mistakes (and how to fix them)
12:49
James Q Quick
Рет қаралды 77 М.
5 Async + Await Error Handling Strategies
18:11
Wes Bos
Рет қаралды 22 М.
Callbacks, Promises, Async Await | JavaScript Fetch API Explained
1:05:05
The Dangers Of Promise.all()
6:15
Theo - t3․gg
Рет қаралды 68 М.
5 Tips for Writing BETTER For Loops in JavaScript
16:15
James Q Quick
Рет қаралды 70 М.
Brawl Stars Edit😈📕
00:15
Kan Andrey
Рет қаралды 58 МЛН