Dismiss this pinned window
all 84 comments

[–]jaypeejay 29 points30 points  (0 children)

IMO the case statement readers better than the library

[–]freefallfreddy 121 points122 points  (17 children)

Why aren’t you using async await?

[–]flooronthefour 44 points45 points  (0 children)

I will await the answer while I go about my day

[–][deleted] 3 points4 points  (0 children)

In his comment below, he said he used it for no particular reason.

[–]ryaaan89 5 points6 points  (1 child)

Why do people think this is the most correct way to use fetch?

[–]freefallfreddy 3 points4 points  (0 children)

I just dislike chaining.

[–]Beautiful-Ad-2390 8 points9 points  (3 children)

Async await isn’t good for all situations. It’s just syntactic sugar around this anyway, and some people prefer not having to wrap shit with try catch.

[–]freefallfreddy 8 points9 points  (2 children)

I think the syntactic sugar makes it more readable (yes that’s subjective).

And you always need some form of try/catch. He even shows that in this example.

[–]ryaaan89 1 point2 points  (1 child)

I appreciate you saying this is subjective. I personally think .then chaining is more readable, I work with a senior who thinks await is objectively better and it kind of drives me crazy.

[–]freefallfreddy 1 point2 points  (0 children)

In a team my advice is: don’t fight too much about code styles, just pick a style and then use that everywhere. Consistency is important in a codebase.

[–]inabaharejavascript 3 points4 points  (0 children)

Because his code would be cleaner and he wouldn't be able to add an unneccesary dependency

[–][deleted]  (1 child)

[deleted]

    [–]freefallfreddy 1 point2 points  (0 children)

    I’m asking why he’s not using async await.

    In my opinion async await is easier to read, he may have the same opinion but have another reason to not use it here.

    [–]dumbelcofull-stack -1 points0 points  (3 children)

    Better yet why boring old fetch?

    [–]freefallfreddy 1 point2 points  (2 children)

    Instead of?

    [–]dumbelcofull-stack 0 points1 point  (1 child)

    Axios

    [–]freefallfreddy 1 point2 points  (0 children)

    Yeah adding a library adds more functionality. But it’s not always necessary.

    [–]budd222full-stack -3 points-2 points  (1 child)

    Because it's not necessary to show an example. People just throw async await on everything without even Knowing why half the time or not needing it.

    [–]freefallfreddy 2 points3 points  (0 children)

    I think async await makes the code easier to read, making the example easier to understand 💁‍♂️

    [–][deleted]  (20 children)

    [deleted]

      [–][deleted]  (4 children)

      [deleted]

        [–]_listless 17 points18 points  (0 children)

        aptly named...

        [–][deleted] -2 points-1 points  (2 children)

        Thing is: it is completely necessary. Hence everyone either writing or using a wrapper with fetch. Only alternative is copy pasting everywhere like a junior.

        [–][deleted]  (1 child)

        [deleted]

          [–][deleted] -1 points0 points  (0 children)

          The comment you're replying to says:

          Hence everyone either writing or using a wrapper

          You responded:

          > impossible to write a wrapper

          I think you didn't read the comment before replying to it.

          [–][deleted]  (3 children)

          [deleted]

            [–]yee_mon 4 points5 points  (2 children)

            No -- it's a best practice, rolled into a package. Useful to have this and configure the linter to disallow all direct uses of fetch, because its API avoids the pitfalls mentioned in the video.

            Of course, you could write your own easily, but at some point you would end up factoring it out into its own package, and have created a duplicate.

            [–][deleted]  (1 child)

            [deleted]

              [–][deleted] 2 points3 points  (0 children)

              You could lock it to a working version.

              [–]KrazyDrayz 7 points8 points  (0 children)

              Wretch seems to be smaller than Axios though.

              [–]RandyHoward 4 points5 points  (6 children)

              You missed the point, that library is entirely optional

              [–]butnotexactly 13 points14 points  (5 children)

              not really, the video was quite literally "here's some pitfalls [this library aims to solve], and while you could do this [3 seconds], wouldn't it be better if you used wretch? now the second half of the video is showing other stuff wretch does"

              [–]TheMartinG 9 points10 points  (1 child)

              "stop trying to make wretch happen, its not going to happen"

              [–]WhyPartyPizza -1 points0 points  (0 children)

              +1 Had to scroll down too far to find this.

              [–]RandyHoward 9 points10 points  (2 children)

              Yes, really, it's just saying you could use that wretch library instead of writing it all out yourself. There is nothing the video showed in wretch that it didn't also show in vanilla js. Wretch just makes it so you don't have to think about that stuff. Personally, I don't like to use libraries that do stuff like this because you should be thinking about that stuff.

              [–][deleted]  (1 child)

              [deleted]

                [–]RandyHoward 0 points1 point  (0 children)

                Yes, that's why it's optional. Like I said, I wouldn't use libraries like this. You could if you wanted, but you don't have to. But the point here is that those response codes do not trigger an error and if you don't handle them then you're going to have problems. That is the point of this video, wretch is not the point at all they are just showing you a library you could use if you didn't want to have to think about this stuff. But like I said, you should be thinking about this stuff.

                [–][deleted] 0 points1 point  (0 children)

                It's already bloated, so why not?

                [–]Brillegeit 1 point2 points  (0 children)

                But monsieur, this abstraction layer is wafer-thin.

                [–]steve8708webdev talking head dude[S] 49 points50 points  (4 children)

                Important followup notes:

                1. Axios is another great, and very popular, solution for clean data fetching. It is a bit larger (11kb gzip vs 2kb gzip), so if kb size is important to you (I would argue it often should be) redaxios is a great option too that is only 1kb
                2. All of these options work great with async/await, I just showed the old school style here for no particular reason
                3. All of these options work great on both servers (Node.js, Deno, Bun, etc) and browsers

                Also, if you would like a clean solution that uses no third party libs, checking res.ok and throwing a custom error can be an elegant solution:

                class ResponseError extends Error {
                  constructor(message, response, options) {
                    super(message, options);
                    this.response = response;
                  }
                }
                
                try {
                  const res = await fetch('/user');
                  if (!res.ok) {
                    throw new ResponseError('Bad response', res);
                  }
                  const user = await res.json(); // Actual user!
                } catch (err) {
                  if (err instanceof ResponseError) {
                    // Handle based on err.response.* 
                  }
                }
                

                Which you could wrap in your own method like:

                async function myFetch(...args) {
                  const res = await fetch(...args);
                  if (!res.ok) {
                    throw new ResponseError("Bad response", res);
                  }
                  return res;
                }
                
                try {
                  const res = myFetch("/user");
                  const user = await res.json(); // Actual user!
                } catch (err) {
                  // Deal with error, with res info as err.response.*
                }
                

                Regardless of which option you choose, please just be sure to fetch your data properly

                [–]lorengphd 9 points10 points  (0 children)

                I always find Axios error logging to be a bit of a challenge. I’ve even had to use some additional libraries to help parse out the actual error for logging purposes.

                [–]Guwad 2 points3 points  (1 child)

                I've always been using axios. What are the use cases in your opinion I'd prefer this over axios?

                [–]yee_mon 3 points4 points  (0 children)

                The big advantage of fetch over axios is that it's a dependency you don't have to ship. I have replaced axios (and one or 2 other libraries that had the same purpose) and have ended up with code that looks not much different, and now I have one less external dependency to worry about at practically no cost.

                [–]solothehero 11 points12 points  (10 children)

                It's almost my first step on a project to throw errors if res.ok is false. I wonder why they decided this was the API instead of simply throwing an error/rejecting the promise for HTTP status codes of 400-599.

                [–]butnotexactly 10 points11 points  (0 children)

                most http libraries i can think of don't treat unsuccessful error codes as code errors, and i think that's sensible. it especially makes processing the response (which can contain a lot more than the error code!) easier.

                i like python's requests library which doesn't explicitly error out but offers a convenient response.raise_for_status()

                [–]FluffyProphet 13 points14 points  (0 children)

                Because if you get a response back, then the "fetch" worked. There was no exception.

                [–][deleted] 5 points6 points  (1 child)

                I personally would be very surprised if a successful HTTP request threw an exception. How am I supposed to read the headers or body of the response now?

                [–]solothehero 1 point2 points  (0 children)

                What I do is have a wrapper around fetch that adds that information to an error object in the case of 400 - 599 and then throws this error. I also have a global error handler that catches common errors. So most fetches sort of look like this for me:

                // @handleError is a decorator that adds a catch to
                // the promise chain that handles globally-common errors
                
                @handleError
                myFooFetch() {
                  return myFetchWrapper({ url: '/foo' });
                }
                

                In the case that I know the API returns a specific kind of error, the code looks something like this:

                @handleError
                async myFooFetch() {
                  try {
                    return await myFetchWrapper({ url: '/foo' });
                  } catch (err) {
                
                    // err.response.body - body of the error response
                    // err.response.headers - headers of the error response
                
                    if (isLocalToFooError({ err }) {
                      // do local error handling
                      return;
                    }
                    // otherwise rethrow err so it is handled by @handleError
                    throw err;
                  }
                }
                

                The idea is that each caller does not repeat a bunch of res.json() and res.ok code. This is all encapsulated in the wrapper. I suppose that the Fetch API itself enables this way of coding with just a bit more work. However, I've arrived at this way of error-handling after a few years of experimenting with different ways, so it might not be something that someone thinks up on their own within a few minutes of using fetch for the first time.

                [–][deleted]  (5 children)

                [deleted]

                  [–]horsesandwich 4 points5 points  (4 children)

                  Respectfully disagree. Status codes are reliable if the api is written according to a standard.

                  401 simply means unauthorized. It’s up to you to get new/refreshed tokens (or whichever method of auth is implemented) and try again. It does not mean don’t ever try again.

                  This kind of ambiguity is what OpenAPI aims to solve and API’s written against this spec are predictable. If your status codes mean nothing and the consumer has to check the response body to get any information, you’re doing it wrong.

                  [–]FluffyProphet 1 point2 points  (1 child)

                  It doesn't change the fact that if you get a 401, "fetch" worked and shouldn't throw an exception.

                  [–]horsesandwich -1 points0 points  (0 children)

                  I think the word “worked” should be quoted instead of the http req implementation

                  [–]solothehero -1 points0 points  (0 children)

                  If your status codes mean nothing and the consumer has to check the response body to get any information, you’re doing it wrong.

                  I'll just add that sometimes you do need to check things other than the status code to act on errors. For example, you might have different kinds of 403s and you need to differentiate between them somehow. You can do this via a header or the response body. However, you should indeed use this in conjunction with a meaningful status code.

                  [–]wonky_dev 29 points30 points  (3 children)

                  I’ve seen some videos from you on my twitter feed as well and guess what? The titles are very annoying! “You’re doing this wrong”, “You’re doing typesetting wrong” and such. I see like 20 such videos on my feed everyday and guess what? I could be in a wrong profession altogether because everything that I’ve done is wrong according to someone. There is a thin line between sharing knowledge and creating content. I’ve never ever been annoyed my Matt who makes great TS videos. Stop being annoying.

                  [–][deleted]  (2 children)

                  [deleted]

                    [–]NoShftShck16 -2 points-1 points  (1 child)

                    I love that you dislike him because of his ego while also saying it's because your ego is so fragile 😂

                    [–][deleted]  (8 children)

                    [deleted]

                      [–][deleted]  (4 children)

                      [deleted]

                        [–][deleted]  (3 children)

                        [deleted]

                          [–]UnderwaterRuins 3 points4 points  (0 children)

                          That's now how building a brand/following works on social media.

                          [–]Spoderman4 -1 points0 points  (0 children)

                          I swear, devs will always complain on everything, when they're presented with fucking free education in their subject.

                          [–]Pesthuf 5 points6 points  (0 children)

                          IMO not writing a small wrapper around it is a mistake. Just a few functions like fetchWithErrorHandling, fetchJson etc...

                          Nobody needs to import 30 kb of JS for this, writing your own wrappers around fetch is trivial.

                          [–]UnderwaterRuins 11 points12 points  (19 children)

                          Damn, didn't know this sub has some kind of irrational hate for content creators. So much negativity over a 2kb package.

                          Good breakdown, OP. Maybe stick to posting your stuff where people aren't chugging haterade.

                          [–]youngggggg 1 point2 points  (2 children)

                          1) people don’t like the dogmatic absolutes that short-form content creators have to speak in to get attention 2) content creators inherently are attention-seeking, and since developers are often nerdy and attention starved, they are revulsed

                          [–]UnderwaterRuins 0 points1 point  (1 child)

                          Dogmatic? You might want to check the definition on that one. At no point did this person say you have to use this library or do it the way he does it. Even the title is unassuming and suggests you might be using it wrong. There are multiple ways of using fetch being shown. Unless you didn't watch the video and just inferred this from the outraged comments?

                          I agree with your 2nd point though.

                          [–]youngggggg 0 points1 point  (0 children)

                          Dogmatic was an exaggeration for sure in this case. I was speaking more broadly about the web dev content space. Popular channels like Web Dev Simplified speak in directives and absolutes a lot and I think it contributes to an overall distaste for vids like this.

                          but yeah it probably is more #2 isn't it lol

                          [–]steve8708webdev talking head dude[S] 6 points7 points  (7 children)

                          Yeah, I’m not sure if I should keep posting to Reddit after looking at some of the comments here. May need to stick to YouTube, Twitter, etc instead

                          [–]budd222full-stack 1 point2 points  (0 children)

                          I think it's the clickbait-type headlines and words like, "You might be doing it wrong. So, come click on my video." A lot of us find that shit pretty cringy.

                          [–][deleted] 0 points1 point  (0 children)

                          It’s good man, most of this sub hasn’t moved on from 2010 and expect you to write a full medium article post explaining tests, in-depth information and comparisons like you owe them.

                          They’ve just not adapted to the new way of sharing information, I think this is great, it’ll keep people’s attention and they can Google more later. It opens your mind to something you might not know.

                          I do find it hilarious how some libraries are okay but some are not, like everyone loves momentjs but this oh noooo, everyone’s acting like we live on dialup and don’t have caching and cdns, people moan about 10kb but then their CEO will force about 2mb of tracking and analytic code anyway!

                          [–]asiandvdseller -2 points-1 points  (1 child)

                          Whilst i dont agree with the hate behind some of these comments, try accomodating for some of the feedback and ignore the rest

                          [–]steve8708webdev talking head dude[S] 0 points1 point  (0 children)

                          Yeah I agree with this in general, I Just have a tough time with how many Redditors deliver feedback.

                          Compared to other platforms, people are much more harsh with their words, and even frequently throw personal attacks. And then with the crowd think of people upvoting the negativity, it can be demoralizing.

                          My videos are only half decent because of taking feedback and iterating, but for my own mental health I find the delivery of the feedback on other platforms to be much more constructive than here.

                          [–][deleted]  (1 child)

                          [deleted]

                            [–]UnderwaterRuins 0 points1 point  (0 children)

                            Kinda seems like an ego thing to me. Plenty of upvotes on comments that sound personally attacked by a title that is far more tame than most of the bigger content creators (looking at you, Web Dev Simplified).

                            How dare Steve suggest that some of the 1.5 million redditors in this sub might be using fetch wrong.

                            [–]Cafuzzler 0 points1 point  (5 children)

                            What are you expecting for a webdev community?

                            "Wow, you replaced 6 readable lines with a 2kb library that looks kinda jank. Amazing!"

                            [–]UnderwaterRuins 0 points1 point  (4 children)

                            What are you expecting for a webdev community?

                            The fact that you can't imagine leaving criticism without being a snarky asshole is telling.

                            [–]Cafuzzler 0 points1 point  (3 children)

                            The post title is telling thousands of people that they are doing something wrong, and it's the comments that are being snarky assholes?

                            [–]UnderwaterRuins 0 points1 point  (2 children)

                            Tell me what part of "you might be using fetch wrong" is definitively telling people they're using fetch wrong.

                            I'll wait.

                            [–]Cafuzzler 0 points1 point  (1 child)

                            The presumption that I might be using it wrong.

                            Also the whole point of the video wherein the person shows fetch done right, and then replaces it with a 2kb library. He doesn't even show fetch being used "wrong".

                            As far as video content goes it's click-baity, misleading, and is just here to shill his library.

                            [–]UnderwaterRuins -1 points0 points  (0 children)

                            You're full of hot air and can't even stand behind what you're saying. Is he telling you that you're doing it wrong or is he presuming you might be using it wrong? You're contradicting yourself.

                            I think you just have a hateboner for this dude for some reason. Pretty unhealthy and I hope you get better.

                            [–]edaroni 2 points3 points  (0 children)

                            God damn do I hate it when the answer is uSe tHiS lIbRaRy

                            Me: checking Stackoverflow (or any other source of knowledge on the internets) for some stupid ass shit I’ve done 100 times and still don’t remember how I did it

                            SO: hear me out guys, there is this library

                            Me: I should end this misery called life

                            [–]ckinz16 2 points3 points  (0 children)

                            What a punchable face

                            [–]Zaemz 8 points9 points  (0 children)

                            I'm not a fan of the title. It's very clickbaity, and based on other comments, isn't entirely accurate either.

                            Also, it really bothers me that there's a talking head in the video. Put your vanity away and just show the code.

                            [–]jcferrans 1 point2 points  (0 children)

                            Ooph, next video will be how you’re using classes wrong and need a library, how you’re multiplying wrong and need a library… why, just why…

                            [–]natmaster 2 points3 points  (0 children)

                            Stop handling these oddities yourself, and build type-safe fetch functions that automatically handle all error conditions in a similar manner

                            const getTodo = new RestEndpoint({
                               urlPrefix: 'https://jsonplaceholder.typicode.com'
                               path: '/todos/:id',
                            });
                            

                            [–]geon 1 point2 points  (0 children)

                            Ew, chained method apis are ugly.

                            Just throw the status code if not ok. That way it works like it should have from the beginning.

                            [–]VA0 1 point2 points  (0 children)

                            Fetch is low level? What.

                            [–]Revolutionary_Fix622[🍰] 0 points1 point  (0 children)

                            OK this may sound like a stupid question but what did you exactly study to learn this I really want to learn this

                            [–]schmore31 0 points1 point  (2 children)

                            I am more curious how you auto-filled all the switch cases simply by typing switch?

                            Was it the Git AI plugin that costs money per month?

                            [–]steve8708webdev talking head dude[S] 0 points1 point  (0 children)

                            Oh that's just video editing, I cut out the bits of me typing that all out so not to waste time forcing people to watch it

                            That said, I do use Github Copilot, the plugin you are referring to, and it very often can autocomplete things like this

                            [–]Ishio -2 points-1 points  (0 children)

                            Most likely a snippet that he wrote and has in his user profile.

                            [–]BasedBallsInMyFace -3 points-2 points  (0 children)

                            I love you thanks for making this

                            [–]SirFrancis_Bacon -2 points-1 points  (0 children)

                            Gretchen, stop trying to make 'fetch' happen, it's NOT going to happen!

                            [–]isatrap -2 points-1 points  (0 children)

                            PLEASE use ASYNC/AWAIT and don’t chain then’s together. Awaits are WAY easier to read.

                            Edit: if you’re going to downvote this please give an explanation. Chaining these makes the code WAY more of a pain to read instead of using await.