JavaScript Fetch API - One Mistake I ALWAYS MAKE!

  Рет қаралды 35,377

James Q Quick

James Q Quick

Күн бұрын

Пікірлер: 101
@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!
@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 Жыл бұрын
This isn't a minor correction.
@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 Жыл бұрын
This is what I always do
@bigbadcatbigbcy2933
@bigbadcatbigbcy2933 10 ай бұрын
oh thanks
@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
@kovoliver
@kovoliver 9 ай бұрын
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.
@ebrahimmehri
@ebrahimmehri 5 ай бұрын
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.
@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!
@juanmacias5922
@juanmacias5922 Жыл бұрын
That makes sense, we should be checking the status code!
@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.
@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
@swildermuth
@swildermuth Жыл бұрын
Great video!
@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!
@ThanHtutZaw3
@ThanHtutZaw3 Жыл бұрын
Quick Question: How can I show fcm notification in foreground instead of toast or new Notification() without action button support.
@Stoney_Eagle
@Stoney_Eagle Жыл бұрын
I'll keep using axios 😂 still gets the job done very well.
@JamesQQuick
@JamesQQuick Жыл бұрын
haha whatever works
@lucneville7925
@lucneville7925 Жыл бұрын
Us too using an interceptor to handle error status codes, makes for a lot cleaner code
@Okir09
@Okir09 Жыл бұрын
Hi James, noob question but how do you get directly your console.log in the IDE next to it? : O thanks
@JamesQQuick
@JamesQQuick Жыл бұрын
It's the Quokka extension. really cool. Highly recommend it :)
@Okir09
@Okir09 Жыл бұрын
@@JamesQQuick thank you!
@JamesQQuick
@JamesQQuick Жыл бұрын
You're very welcome! That's what i'm here for!@@Okir09
@AlThePal78
@AlThePal78 Жыл бұрын
Great video
@jordan4220
@jordan4220 Жыл бұрын
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 Жыл бұрын
Ah yes another great callout!
@AlThePal78
@AlThePal78 Жыл бұрын
Could you make a status switch statement
@JamesQQuick
@JamesQQuick Жыл бұрын
Absolutely you could!
@AlThePal78
@AlThePal78 9 ай бұрын
why do you have import here? Is it because it is a REACT.js fetch?
@ondrejhavazik4124
@ondrejhavazik4124 Жыл бұрын
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 Жыл бұрын
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!
@BorisBarroso
@BorisBarroso 2 ай бұрын
What I do is throw an error if the status is not 200 and you can sometimes prase de json and send as error status ===422 let errors = await resp.json() throw errors
@nopainnogame9897
@nopainnogame9897 6 ай бұрын
if I check if (!response.ok) {} is it not the same?
@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.
@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
@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
@alexanderkomanov4151
@alexanderkomanov4151 Жыл бұрын
Great!
@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
@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
@ifeanyinnaemego
@ifeanyinnaemego Жыл бұрын
Nice one
@alexanderbelkin5978
@alexanderbelkin5978 2 ай бұрын
Лукашенко одобряет!👍
@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
@bigbadcatbigbcy2933
@bigbadcatbigbcy2933 10 ай бұрын
good to know
@harshvardhanthakur4688
@harshvardhanthakur4688 5 ай бұрын
hey its helps me
@BoZZstuDIOSin1981
@BoZZstuDIOSin1981 Жыл бұрын
thx.
@JamesQQuick
@JamesQQuick Жыл бұрын
You're very welcome! Have you made that mistake before?
@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.
@VivekYadav-up7uu
@VivekYadav-up7uu Жыл бұрын
Nice
@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
@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 :)
@GildwareTechnologies
@GildwareTechnologies Жыл бұрын
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 Жыл бұрын
wtf is this chatgpt type of response lol
@JamesQQuick
@JamesQQuick Жыл бұрын
bahahah feels like it!
@omega.developer
@omega.developer Жыл бұрын
🎉
@vatmanzlokuz680
@vatmanzlokuz680 5 ай бұрын
wtf,who deserialize a request without check status code xd
@liu-river
@liu-river Жыл бұрын
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 Жыл бұрын
I made this error yesterday, stole about 30 minutes of my life 😿
@JamesQQuick
@JamesQQuick Жыл бұрын
hahah glad to know I'm not the only one
@MrMudbill
@MrMudbill 2 ай бұрын
if (!res.ok) throw new Error()
@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
Tips For Using Async/Await in JavaScript
16:26
James Q Quick
Рет қаралды 396 М.
JavaScript Error Handling: 5 Things You Aren’t Thinking About!
14:42
Chain Game Strong ⛓️
00:21
Anwar Jibawi
Рет қаралды 41 МЛН
How Strong Is Tape?
00:24
Stokes Twins
Рет қаралды 96 МЛН
How to FETCH data from an API using JavaScript ↩️
14:17
Bro Code
Рет қаралды 170 М.
JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue
12:35
The TSConfig Cheat Sheet
5:36
Matt Pocock
Рет қаралды 38 М.
Stop Using JavaScript Fetch - Do This Instead!
6:16
James Q Quick
Рет қаралды 14 М.
Only The Best Developers Understand How This Works
18:32
Web Dev Simplified
Рет қаралды 115 М.
GET Data from API & Display in HTML with JavaScript Fetch API
5:50
Is Next.js 15 any good? "use cache" API first look
8:16
Beyond Fireship
Рет қаралды 127 М.
Top 5 Async Mistakes for JavaScript Beginners (Don’t make these!)
15:11
The TRUTH About Golang Backend Frameworks
6:31
Melkey
Рет қаралды 134 М.
Chain Game Strong ⛓️
00:21
Anwar Jibawi
Рет қаралды 41 МЛН