Vue 3 Hooks and Type Safety with TypeScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello youtubers i'm going to show you something special today i'm going to show you something here that you're going to be using on every project moving forward especially if you're going to be using typescript in view 3. okay so what i'm talking about is a composable api hook so it's a way to load apis from one centralized location using composables for hooks in view three so i used some of that or i've been using some of that for about five years now or so and i love it i use it on every project so far and i'm sure you're gonna be stealing this and bookmarking this video for your future reference so our goal today is to create the centralized composable hook for communication with apis and then two we are going to be using that hook to create a new composable hook based on the first hook so we're going to be composing a lot of composition here folks another hook for just for loading those products all right and three we are gonna be using typescript so we're gonna be setting up some uh proper type safety in this project now this is gonna be useful i hope stick around and let's get started i'm going to be using the same project so i just started this view 3 project with typescript if you want to know how i did it take a look at this video and get started right away so nothing in here it's just defined component for proper working with typescript and view three now what i'm going to be doing is i'm going to be creating new composables so right now i'm going to create a new folder i'm going to call the compo siblis all right this is going to be you know my hooks i could have called it hooks or modules whatever you'd like i know in one of the recent videos i called this modules now i'm calling it composables i still need to figure out what the right terminology is so this is going to be api dot ts we're using that script people see it's going to be ds not that view because there's no view right no template just dot yes good old-fashioned typescript so i'm exporting a function export default and i'm going to call it function use api alright so what i need in this is going to be some kind of url because we need to we're gonna need to connect to something and some kind of uh i guess options all right no type safety right now nothing i'm gonna fix that in a bit i do expect some kind of a response right some kind of data that's why i'm doing this so response is going to be um ref okay where did we get the ref from let's import ref from module view oh yeah i like typescript because my vs code is giving me hints so we have the response and we also need the request and the request is going to be a function and it's going to be an asynchronous function right because we are using the fetch api let's see how this works the response is going to be a weight fetch right because i'm going to be fetching something with the url that i mentioned above and the options that i may have mentioned above and then i need to format that because i expect a json so i'm going to play safe or simple here this could be json this could be text right but for the simplicity sake of this example i'm going to assume that we are getting back a json right it's going to be an object an array or something let's call it data it's going to be await response.json that's nice and now that we got this we need to feed that into our response response that value is going to be this data yes all right so this is it uh what did i write here i wanted to request now i probably need to return something so i'm going to return response and i'm also going to return request so that whatever consumes this function knows how to work with this let's save i got all my auto formatting done okay i already see some red lines right under url and their options this means typescript is telling me hey we need to secure this okay this is the hard bit are you ready so let's add some types into this example okay if i if i run this project with serve you know typescript is not going to let me fly with url and options not typed so what do we have options has any type and url is also going to be empty right or any i'm sorry so i need to fix that let's close the terminal and let's focus on this bit i have to deal with the url first you know typescript thinks it's any but i want to use the same type with fetch and let's see fetch says the input argument is going to be request info let's just steal that from here request if i like that better than string and then options okay first of all i'm going to say it's optional and then i'm going to extract the exact type that we should be using here and that's going to be a request in it so let's stick to this for now when we're going to come back and improve this as we go on so the next thing that i want to fetch is going to be some products okay let's create a new file new composable called products.typescript nice so we're doing the same thing okay export default and this is going to be an asynchronous function because i want to load them as soon as possible load the product so function use products okay i want to load all of them inside this i'm going to be using our use api okay use api composable and i'm going to import this import use api from well right here right api okay this is good so we have use api let's confirm that this is going to work fine and i need one or two arguments that's fine i'm going to add them in a bit what i get back is response and request all i need right now is response and i'm going to rename response to products now this is fetching response but i'm going to be using the variable as products okay use api requests the url i already know what my url is and this is a sample a cloudflare worker that is going to fetch us some products now i want to create another ref i'm going to say loaded is going to be ref and it's going to be false by default okay so ref i don't know where this comes from okay import from view right i love this autocompletion or intellisense loaded is going to be false and then if loaded without value because we use ref so we need to use that value if this is still false then and only then load upload a wait request but hey i don't have requests because request had to come from user api of course i totally forgot about it so request is going to be this function so if it's not already loaded then a wait request that means load my projects or products i'm sorry and then loaded that value is going to become true all right so this means whenever we use use products we need to load the products immediately but do not load them twice now we have this flag that works properly and it's going to set it to true meaning hey we already loaded our components now we can add a lot more uh error proofing in this example so that if there is an error we need to work this through but right now i'm going to set that as is we already talked about using error boundaries in this video right here and you can take a look at it if you want to know more about that but right now this is going to be just enough for this example finally i need to return some products back so that my components can use it i'm going to save this real quick okay let's recap i'm gonna fetch the request function which is an api and you know what else i can use the split screen here okay this is my api and this is products okay this is gonna be good so use api is this function that requires a url i'm i'm providing the url right here and i also need request which is right here request is going to fire fetch format as json and return that data as response i'm using response and renaming it renaming it to products so that i know exactly what i'm working with let's go back to hello world i'm going to consume it right inside hello world so it's kind of easier we have the setup function right here and i need to import my composable import use products from i'm going to use this add placeholder this means everything that starts from the application root so i don't have to worry about relative resolving of modules i'm going to resolve that automatically based on this at sign this means from the source folder so composable let's composables it's right here i love autocompletion products exactly what i needed so use products right here i'm going to delete this console.log from our last video and i'm going to say const products okay let's check that so we get return products const products is going to be use products composable okay now i need to do something with used products and i'm going to return products but this is not going to work out of the box because i need to await why a weight let's actually let's show it here products i need to wait because this is an astronauts function and inside the function body we are awaiting another request right which means this function is just going to return a promise unless i put a weight a weight used product means it's going to load and then return the products as they become available from the response i also need to use async setup okay now i would say that this is everything we need but it is not as you may have seen in my other video on using suspense we actually need to use a suspense boundary when using async setup right what does this mean just recap this means that if there is an asking setup it means that that component uses promises and suspense is going to recognize those promises and wait until the promises are resolved maybe we can think of suspense as views declarative asset wait kind of i think i kind of like that okay so we need to wrap hello world in a suspense boundary let's go back to app.view and wrap hello world in the suspense bathroom it's gonna be very easy i assure you go back to app view and this is very simple suspense right here okay enclose suspense in my previous video we saw how we can use templates for fullback and default when this hello world has been successfully created well you know i can do that here as well so template this is default right this means whenever the promise is resolved close template and i'm going to create another template it's going to be fallback right close template so my full back is going to be some kind of div that says loading right okay template suspense this this would work fine go back to my hello world just double checking this i need to do something with these products okay i'm reusing these lists added so there's gonna be a v4 loop okay product in products and i'm gonna loop through these li so the key is going to be product.id because i know i have that id and inside the li i want product the title okay saving and let's double check this is working fine and let's show in the browser boom okay look at that a generic soft keyboard you know and a bunch of other stuff okay let's uh let's go back and you know why this is showing that ugly because we have li as inline block all right let's let's go ahead and remove this and i'm also going to remove some of the other content and say products i'm going to remove these other ul's from the hello world application just some cleanup to do okay it's already reloaded it's that fast and ladies and gentlemen this worked just fine look at that all the products let me walk you through this for a second maybe the question is why are these products loading without an error so i'm fetching products eventually this is going to be undefined until products are fetched however because i use async setup and i'm loading the products from an away from asking away from promise suspense is going to wait until all the promises are loaded meaning my request is loaded and then my products are ready and then the async setup function has finished with all the promises that are nested right once everything is ready only then will suspends render this function which means that by that time my products are loaded and they are no longer undefined unless there is an error and then we have to worry about that too now i want to say congratulations you've done it you're able to do this but i wanted to take you a step further i wanted to properly type this and you know you're gonna thank yourself for properly typing functions so you know exactly what to expect it's gonna catch any bugs very very early on in my favorite thing it's gonna your your id hopefully is gonna use that as intellisense it's gonna give you hints what to do what not to do right let's go back to our user api hook and let's add types okay this is going to be a bit more difficult or tedious but it's going to be worth it before we go there if you like this video so far you know you can hit the thumbs up and like it feel free to subscribe to our channel because we're going to be publishing a lot more of those a lot more videos from the trenches a lot of cool content on the way so let's get back to this example right now so what do we have we have the api.t.s in this left-hand window and products right here so let's break it before we fix it the first thing that i know is that request is going to be avoid promise right so type api request is going to be a function with a promise and because i'm not returning anything it's going to be void right okay so api request is going to be this function now the trick is how do we type response and i don't know what we are going to get back but because this is a composable api i want the products composition or hook to tell me what to expect so to do that i'm going to create this new type i'm going to call t and now this type is kind of a placeholder that i can forward i don't know what it is but whatever it is i want my response to be it but the way i'm going to define that response is by using that t not just a t because this is going to be the ref right so i'm actually going to say this this is a type ref type ref and then it's going to be t or it could be undefined because in the beginning it is undefined until it becomes t ref i'm getting from view right because now i'm talking about a type not a function ref is going to be t let's double check right ref is going to be t or undefined and my request is going to be the api request now if i check the return i said response is going to be reft request is going to be the api request type that works beautifully i also like to export every type so i can reuse that somewhere else although we are probably not going to be importing it but let's go back to products now the products this is the place where we're going to add a lot more type safety okay i know a little bit about my product so i'm just going to paste the type that i have ready so we have variant in product let's go back let's go down from product this is the product uh data that i get back from uh the api request it has the id title and so on one of the cool things we have is the variant is those sku where sku numbers or ids and variants so this is going to be a variant it's going to be an array of skus and that's typed right here this is very specific to the api that we are making and now that we are teaching our application to know what data to expect we can properly use that type safety within our application and also our intelli sensor is going to know exactly what kind of data we know we're gonna get from the api i love that okay it's time to use this type i know we're gonna get an array of products in fact not just one and this is a place use api okay you see this use api then this t okay use api and this is going to be product and then i'm going to say products plural by specifying that as an array i expect multiple products from my user api so this way i know that products it's going to be see that the script is so beautiful it knows automatically that my product is going to be an array okay i'm saving this i'm getting a little bit of auto formatting done and this is it we can go to a greater detail but this one trick is what i thought is worthy of knowing if you follow this concept every time when you work with your view 3 application i highly recommend going with typescript and if you follow this concept you're going to play it safe let's check in the browser and this works beautifully you see if i reload it totally works i hope you like this example of using a view 3 composition api and then composing on top of composing with typescript i hope this was as much fun for you as it was for me please stick around we have a lot more content to show with you see you in the next episode goodbye
Info
Channel: Modus Create, Inc.
Views: 6,482
Rating: undefined out of 5
Keywords: Vue 3, Vue Js, Getting Started with Vue Js, Using Hooks in Vue JS, Composition API Vue JS, Vue 3 Typescript, Vue 3 and Typescript, Vue 3 Hooks with Typescript, Typescript and Vue 3, Vue 3 Type safety, Type safety in Vue 3, Typescript Vue 3 Hooks, How to use Typescript in Vue 3, How to use Vue 3 with Typescript, Vue 3 Tutorial, Vue 3 Typescript Tutorial, Tips for Vue 3 Typescript, Typescript with Vue Tutorial, Can I use Vue 3 with Typescript, Typescript tutorial, vue 3 ts
Id: aJdi-uEKYAc
Channel Id: undefined
Length: 21min 4sec (1264 seconds)
Published: Thu Oct 01 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.