The simple way to handle requests in React

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up guys teros cin here in this video I'm going to show you a very simple way to handle your requests in react in case you're not using or you can't use something like react query all right cool so as usual we're on my computer screen and we can begin what we're going to be building in this video is a request Handler that is going to handle our requests for us in a predictable and controllable way for this we're going to be using the axus library but you can do this with fetch if you want or you could do this in any other way that you want the beauty of this is that you get to completely control what the API looks like for how your requests are handled and you get to use any library that you want and you get to configure how your responses actually look like so what we're looking at right now is an empty file called reques handler. TS in here we are going to build our request Handler but first because we are working in typescript I'm going to start by creating the types that we need to build a request Handler and then we're going to proceed with building it the first type that I want to work on is the basee request this is going to be the request that we give to our request Handler for it to handle the request for us essentially it's going to be the axus instance that Will Call some endpoint to fetch some data so I'm going to do type base request and this one is going to be a generic type from typescript so I'm going to give it here two letters t and then V and if you're not familiar with generic types essentially these letters t and V are used to represent the actual types that we're going to give this whenever we are using this in our code but for the type definition that we're doing right now we don't actually care what T represents or what V represents all that we care is that we have a letter to use them in our type definition so I'm going to make here a space I'm going to do enter and then create a parenthesis and this is going to be a function that is going to take in an optional parms so I'll do parms question mark option and then I'm going to give this T right so here we have this T that we give whenever we use base request that t is going to go as the type of these optional parameters right here that is in a nutshell how you work with generic types in typescript and this one is going to return a promise but because we are working with axios it's going to be an axos response so axos response which I can import directly from axios and this one is also a generic type which means that we can give it something and I'm going to give it here V and I'm going to close this and save now to keep things simple for the rest of this tutorial this T here is always going to WR represent the type of these parameters and V is always going to represent the return type of whatever we're getting from the API so now that we have our base request we can start typing our base response but for our base response we need to handle two cases we need to handle the success case and we need to handle the error case so I'm going to come here and make a new line and start defining our success response so I'll do type success response this is also going to be a generic type but this time only taking one argument V the actual value that we're going to be returning and this one is going to have two properties the first one is going to be code that is going to be success this is a string literal and data which is going to be of type V right so we have our success response it takes in a vtype argument and will return a code of type success a string literal that can only ever be success and then the data which will be of type V then we can come here and create our error response so I'll do type error response this one is also going to be a generic type and here we'll give it e to represent our error and then this one is going to have code error and then error is going to be e save this and we have our ER response which looks very similar to Our Success response now one thing that I want to do is to give a default value to this error here because we are working with axios we're only ever going to expect one type of error that's going to be be an axos error there's no other errors that we expect here so we can safely give this a default value of axio error import this directly from axos so that we don't have to provide this every single time right and this only works because we are using axos and this is the only error that we could ever expect cool so now with this we can start defining our base response so I'm going to do type base response this one as you can hopefully have guessed by now is also going to be a generic type it's going to take two arguments V and then e and this one is going to return a promise of either a success response and we're going to give it this V here or it's going to take an error response and we're going to give it the E here as well close this and save so our base response is a generic type takes in a value and an error and then returns a promise of either a success response or an error response and passes the value and the error to these corresponding types and this is one of the benefits of using generic types in typescript is that you can pass them around which makes this really really useful cool so now with this we have everything that we need to start building our request Handler so let's make a new line and let's do export const request Handler this one is going to take in a function and it's going to take in a request so we'll do request and for now we're not going to give this any types I just want to create the whole function first and then create types this one is going to return another function that will take in params and this one is going to return for now just an empty object we're not going to implement this right away this is our request Handler we're going to use this to create our actual request functions get this request call them with the parms and then return in the implementation here either a success response or an error response now what we need to do is we need to get rid of these red squiggly lines and actually add our types so first I'm going to come here at the beginning of of request Handler and I'm going to give it some types here I'm going to do t v and then e and in this case we have to default e here like we did so I'm just going to copy this and paste it here just so that whenever we're using this request Handler we don't need to always provide the error the error is always going to get defaulted to an access error and then we can come here to our request we can give this a type we'll do base requests and then we're going to give this T and then V right so this is the type that we created here here which returns exactly this here right so we've typed it here let me just save so we have some formatting then we need to type our params which are going to be super easy just like we typed them here as optional T we're going to do the same thing here as well so optional and then here come here and then do T right this T will come from here and now this is going to return a base response of v and then e right and we can save this and now we do have an error which is basically that we said that this this is going to return a base response but we haven't actually implemented anything so the next step for us is to actually implement the response cool so now we can actually begin implementing our request Handler but first there's something that I forgot here we need to put a sync because this is going to be if I can type because this is going to be an asynchronous function that is going to return a promise right base response is a promise so we need to have this async so we'll come here and then arguably this is going to be the simple part of this whole exercise we can just do try and then we can do const response equals the request we're going to await the request with the parameter so co-pilot is being very helpful so we're using this request and we're using these parameters here and we're calling the request with the parameters we're getting then a response and then if we have a successful response which is only going to be inside of this Tri block we can just return an object with code success and then data response. data right so this is our base response here right we're using the success response and we're passing it as data our data here and because we did it this way we are automatically getting type inference we know that this data is going to be of type V right so that's really really cool then what we can do is handle our error case so we'll do catch error and then here we're going to do return code error and then error error as e and actually I'm going to just put e here instead of error and then do e here and here we unfortunately have to typ cast our error as e because there's no way for this piece of code to automatically infert the type so what we have to do is we have to typ cast it so that this will work as we expect so now with this we've successfully created our request Handler so this request Handler will take in a request we'll call that request with these parameters and then we'll handle this piece of logic and and then if the request is successful it's going to return to us code success with the data otherwise it's going to return code error with the error that we can then use in our components now the really cool thing about the fact that we did it like this is that for one here we can provide any success response that we want here we said that we just provide a code of type success and then the data but you could have done anything here you could have provided the success status code of the response or even the entire response right it's completely up to you and the other thing is that we don't have have to necessarily use axios we could have used fetch here and if we did use fetch all that we would have to do is change some of these types to work with fetch right this is beautiful because if later on in the road you decide you want to change the way you make your API request from axess to fetch you can just make the changes here make the changes to your types and then return the same response and your code is going to work without a problem cool so now we have a request Handler that's fully functional the next step for us is to actually use it to see how this works so I'll come here I'll create a new file call this users. TS and then this is going to be a fake API we're not actually going to be fetching any data just so that you get to see how this would work in a real application so first we have to import axos from axos and then we want to import request Handler from request Handler which we just created and then again because we are working in typescript we need to start creating our types so first I'm going to create interface user and I'm going to just give this ID of type number and then name of type strip this is going to be the return type of our API and then what we want to do is we want to create a type for our pars right so we'll do interface get users parms and this is going to be limit question mark number and then page question mark number right this is simple it's pseudo code almost we're not actually doing anything with these but in a real application you would have some sort of parameters limit offset the page filters whatever else you want we're going to be using this to build our actual API function then we can come here make a new line and start creating our get users function so I'll do export const get users this is going to be equal to request Handler and this one is going to take in some types the first type is type T which is going to be the type of a param so we'll do get users params then we have the return type which is going to be an array of users so we'll do user and then this and then we'll close this types call the function and then open a new parenthesis and here we can pass params and this one is going to return to us an actual API endpoint so we can do axios do get and then we can call our imaginary API API users and then we can pass it here parms save this and we have our get users function which uses the request Handler gives it the proper types and then we'll will actually run this axus doget function so then this request Handler is going to call this function with the PRS here this is the request this is exactly this request here it's going to call that with the PMs and if it's successful we'll return this object here with code success and data response. Theta and if there's an error it's going to return code error and then the error as an object so that we can use it in our application this is really beautiful because it makes things very simple you can create these in your own file and Export these to use in your components so we can come here we can open a react component this one is a server component it's an as synchronous function but you can do this in a client component with use effect if you wanted to it would work exactly in the same way so we can come here we can do const users response equals await get users import this directly from API users call this function again we can give it some optional parameters for example a limit of 10 and a page of one right again this would come from your state or from some other place if you're in a synchronous component and then we have this users response here which if we hover over it is either going to be a success response of a user so again all of our types are properly inferred or it's going to be an error response with an access error right so that's our types here so what we can do is we can do if users response. code equals equals equals error then we are in an error case and what we can do is we can return div and then we have access to the error so we'll do users response. error. message and this is going to be directly the error that comes from axios which is why we have this automatically typed this is going to be of type string because we have defined this as a default to be axus error right so everything works super nicely and then the last thing that we need to do if we are here we can just do users response fs. dat. map and this is going to be a user so we're going to do user and then we can just return a div with user.name and here we can give it key user. ID save this and then we have our API fully functioning we've fetched some data if we have an error we can return the error case otherwise we just map over the data and this makes for a really clean API because the error is handled elsewhere we don't have to put try catch blocks in this component directly and we automatically have type inference in anything that we do if we have an error we get the error here that is properly typed if we don't have an error and we actually have data we get the data here that we can use in our components this is a really really simple way to handle and structure your react fetch requests and you do it with only a few lines of code because really this is all that you need so there you go guys that was a simple way to handle your requests in react once again if you have the opportunity to use something like react query you should absolutely go and use that because that is a better alternative to this and it gives you a lot more this was specifically for cases where you can't use it or you're working within a project that didn't use it from the start and it doesn't make sense to convert everything to react query now and as a byproduct to this as something that's really cool we've also got to work with generic types and typescript which is always a good thing and I think is really useful for all of you if you enjoyed this video as always you can click here to subscribe it would really help me out a lot it would mean the world to me you can also click here to watch a different video of mine which I'm sure that is super super awesome because YouTube is recommending it to you and with that being said my name has been darus caen this is caen Solutions thank you so much for watching and I will see you all in the next video cha cha
Info
Channel: Cosden Solutions
Views: 21,695
Rating: undefined out of 5
Keywords: react tutorial, react crash course, react developer, learn react, react hook, react hooks, react hooks tutorial, programming tutorial, react hooks explained, computer science, tutorial for beginners, react component, learn programming, web development, frontend development, coding for beginners, simple code, easy programming, react, react native, axios, axios react, fetch react
Id: TahUv8LH-zA
Channel Id: undefined
Length: 15min 43sec (943 seconds)
Published: Fri Nov 24 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.