VueConf US 2021 | The Vue 3 Composition API by Natalia Tepluhina

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and thank you for listening to my talk at viewconfuse this conference is special for me because last year it was the last offline event before lockdown started and i have the warmest memories about it really hope that next year we will be able to see each other offline in real life but so far let's enjoy our online interaction and today i am going to speak about the composition api yes about the composition api again i know that there were many talks about these but this one is a bit different because i'm going to focus on the practical side of things and how can you use composition api in your application and why would you use a composition api in your application the first short part of the dock going to be slides with a very quick explanations of things but we will get more about it in the life coding part and main question i will try to answer here is what problem do we want to solve with composition api because i've seen so much misunderstanding about it like should we use composition api shouldn't we use it like a vast majority of users prefer options api and they do but i believe there is a part of the code where using composition api might be really beneficial and i will try to show this one let me quickly reintroduce myself my name is natalia dubluhina and i'm vgs core team member i care mostly about view documentation and if you're at view3docs there are high chances that you are doing something that i wrote and i work as a staff front-end engineer at gitlab and honestly in our code base we have so many places where composition api would be great i'm really waiting for migration to view three that's why i wanted to show this in this talk and i'm also a google developer expert in web technologies so let's jump to the composition api and if you happen to never heard about what is it it's an api that allows us to create standalone reactive state or properties outside of few components because in view 2 we were kind of bound to the component scope to have some reactive state view 2.6 fixed it a bit introducing view observable but it wasn't widely used and it was rather experimental one with view 3 you don't really need a component anymore to create a reactive state and when i'm speaking about reactive state this means that changes of this state will trigger changes in let's say rendered template here we are creating a standalone property actually two standalone properties with uref method and this will create two reactive objects with a single property value and then we can import them use them in view components or outside a few components so if we want to use them in our view component we need to create them inside of the setup which is a new component option in view three return them from the setup and then they are available in view template or other options if we want to use them and here we are simply building two v models onto inputs connected to these reactive properties we can abstract reactive state what does it mean sometimes setup in view components can get really bloated with creating many reactive properties that's why it would be nice to have them abstracted in the standalone javascript files like i'm doing here with the use form so here we're exporting function use form and from what i see most of people myself included prefer to call this a composable so use form is a composable here where we're again creating two standalone properties and the function for submitting the form and we return them all to be used in the view component so here we're importing our use form we do call it it returns whatever we need we return it from the setup yes i know this part about returning things as an object is a bit annoying but that's what we need to do for properties to be accessed in the template and we can use them this quick overview is still not answering why this api is useful and if i was asked this question and i needed to give a short crispy answer it would be flexible universal logic composition in view two we had a few ways for logic abstraction and composition but it struggles a bit with flexible and universal combination so for example we had mixins here is a mixing that will create two reactive properties login and password and we'll submit the form and it seems legit it would work with when imported in the component but what if i want to also pass some unique parameter like i would do with a function what if i want to pass a form id and with simple plain mixing this is impossible they don't accept parameters they are not flexible at all of course you might say that i can create a mixing factory but again it creates more complications in the logic than it should and it's still not flexible enough yeah another option would be creating a runnerless component that exposes a single default slot and through this slot we are exposing the properties from the child reform wrapper component again would be login password and submit form and we can call everything we have reactive properties and of course we can pass a prop form id here so our idea about flexible is not that problematic anymore but this is truly universal what if i want to access the login property somewhere outside of form wrapper in the template and this is a problem because with renderless components we are bound to the runtime we cannot access everything that is exposed from the child component somewhere else in the template or maybe in component options and this is still not as universal as we want it to be so let's try to solve this with a composition api let's try to build a flexible and universal abstraction and for this we will be using different apis i was going to create a composable that will call an api handle loading and error state and no matter what api is it should work so i will be using the cat api as my first api because i simply like cats and it's easy and understandable but for the next apis we are going to use an almighty random and this api will that will select two additional apis for us let's pin the wheel and choose an api the first one is going to be anime and second one this is rest api by the way and second one is going to be rick and morty this one has rest and graphql options and i will probably play with a graphql one so let's go to the id and run an application this one so far is very plain this is just an input field where i plan to add a search for my api and we will build everything on top of this so let's start creating our reactive properties of course to have a search of the api we need to create something called query and this will be a ref with an initial value of an empty string and let's start returning things from our setup here we are going to return the query and i want to add v model to my input so we will have to weigh biting with a query as you can see i'm not using query value here because for template it's already unwrapped and of course i will need some result again the initial value of an empty string and i want to have a method that will be actually calling an api it will perform an axios call so i'm uncommenting axios here and i will call it call api it's going to be an async method that where we will have a result awaiting of the access call so access get and let's go and copy paste the url so we have our cats we will be searching by breed here we go i'm fetching this grid id and instead of braid id here i will put my i need to replace a string to the string template and here i will be using my query value good and let's console log our rest to see what we are fetching from the api i will also return result and call api from here and i will run my call api when i'm clicking the search button okay let's try to type something and see what we have as a response where is our console so i'm trying to search for cat i'm calling the api and i have some kind of response where i have breathes and url this is actually the url i want to have from the result so it will be result data zero url yes data zero url right let's go again with abyssinian cat yeah i have an image let's display this one in our interface here there will be an image the source and let's insert set of console log these let's make a result value assigned with a rest data zero url so result and also some random image not really useful but it is what it is and i only want to show this when i have a result okay should be a bit more interactive now okay i forgot to make it dynamic now we have a cat this is nice but it would be also good to have some loading and error state like in real life application when we're loading an image or maybe something happened and the image is not loaded so let's start adding more things on top of this so here i will have a block for error and let's say oops something went wrong please try again and i want it to be red so i have a specific class for just coloring it red and of course we need to add more things here i want error to be boolean so the initial value of it is false we're not hurt immediately when we started an application and let's also add loading state again should be false until we actually start typing and searching in our input let's also show a loading here with a simple we if loading i don't want to add any fancy spinner it will be just text and here if we're not loading we will show a result so when we start in the call api let's say that error value is false loading value is true and let's add try catch block try catch and finally so in try we will be calling the api if everything is fine we will be assigning the value in catch if something went wrong we will say that error value is true then finally we need to set loading value to false whatever happened okay and of course we need to return our loading and error states from here first of all something and secondly i need to add v if error okay that's not let's try to search again for cats so there is loading state there is an image and if i break something like this there should be an error so yeah something went wrong please try again awesome we created very basic api color and we already see that our component became a bit bloated so maybe we could abstract this logic and move it to some composable to play with it nicely inside the component after let's go to our composables and create some use api js which is going to be our composable and i will import ref method from view immediately because this is something we want to have here and let's copy paste the logic we will modify it slightly in our function so i'm exporting function use api and here we go so what we're going to keep here first of all we are going to keep all the reactive properties because every single api call we want we will have a query which is a search term a result of course call result error and loading state do we want to keep an axios call here i would say no because what if i'm going to use a different method to fetch my data maybe i will switch to apollo client maybe i'm going to use native fetch maybe i will be retrieving the data from somewhere else maybe reading local storage i don't know so i don't want to have an axios call inside of the composable instead i will pass a method here called get results and when i'm performing a try i will just call get results and this method should be somehow connected with a search term that is stored in this composable so when i'm calling get results which will a function i want to pass my very value here from the reactive state again there is some shape in here so we are checking data zero euro and i don't think that we need it because it will be defined in the external component depending on what way of fetching data we use we will be shaping them there instead we will simply assign the result of the get results to our result value and of course we're going to keep error value and loading value logic here so here is the composable in the component let's import our use api from our composables and let's replace the logic here i will remove reactive properties so far so we want to get everything like this is equal to use api call and we need to pass a function here so i will have a query parameter and a function so here i'm going to call my api await access get i don't need value anymore because we already passed query value from our composable so it's just a query and i want to return my data shaped so it will be rest data zero url and of course i need to remove all the call api scene from here okay now let's go and check if we broke an api ref is defined but never used yeah we don't use it here anymore okay let's search for abyssinian cat and we have an image so our abstracted logic like this is working nicely like more cats okay let's search for something else siberian yes this is siberian cat so we have the cat api working and i will comment it so we see this is for cat api let's go and use more different apis so here is an api to fetch any kind of anime and i'm going to use the same composable to fetch and show anime posters so with the only thing we need to check that we will use this endpoint and we need to filter it with text so let's add anime api and i will copy paste the logic for now the return should go to the end anyways this is common for everything and let's copy paste this part oops i need also to move a curly bracket to the end okay let's command the cat api and we will copy paste this anime and to we need to add a filter and i just remember that it's filter by text is equal to our query of course this won't work because the respawn should have a different structure so let's simply make a console log of response to see how to shape the data and let's close our documentation and go back here so i will be searching for bleach search something went wrong of course because we are trying to shape an api that is different it's not like crash zero probably arrester is not existing even so we have data data where we have an array i will just be using only the first element so data data zero attributes poster image original okay let's try to recreate it here data data 0 attributes now cover poster poster image original so flaky again which search so i have an image here and now i need to return this to my composable one more try which search and we have a bleach poster here let's be respectful to view three and search for one piece and here we go so our composable is working with two apis already now let's be fancy and use rican morty api and show the difference i want to use a graphql version of it as you can see i already have a query for fetching characters with filtered name reek and it's going to give us a list of characters i'm not going to explain graphql api here but we're basically shaping the response with a request and this should be a query string so let's again copy paste with what we have here and have freak and morty api and i will just paste it and command this one so rick and morty is graphql one which means that we will be changing our get request post one we also need to have graphql query itself i will create a characters query this is just a string and i will copy paste everything from the explorer so we shape the string here and we need to make a small change i want to pass name as a variable and when you work with graphql queries you can pass variables there this way so i'm creating a variable called name which will be string and i pass it to query looks a bit cryptic but if you work with graphql you know this is the way to do so here i will be using post and as a url we are going to use rick and morty graphql api and as you can see query is done here we will need to add it to the body and our post request body will have the query and this will be our characters query and variables and as variables as you can see we're passing a name name will be our query so we have our post request and let's make a control log press okay let's go to our application and search for ic of course it complains because again we have a different shape but you can see that we have a response and response has data with characters array so now we need to perform all the logic to retrieve an image from here so data data characters results zero image press there would be data data characters results zero first result image let's hope i was correct so we search for rick we have an image awesome now let's take this return into our composable remove the console log and let's search for more tea just to make some difference and here is morty and this is actually my face right now after everything just worked so we have three different apis and the same composable that works for all of them luckily and you can see that the logic that we left in the component is just connected with an api call specific itself and it handles loading and error and everything we want to so if you wonder how the code looks like at the end here is a repository with a final result of all the composers i think there is no rick and morty there only cats and dogs but you can recreate it yourself and thank you for listening to my talk
Info
Channel: Vue Mastery
Views: 8,118
Rating: undefined out of 5
Keywords: composition api, composition api tutorial, evan you, vue 3, vue 3 composition api, vue 3 course, vue 3 tutorial, vue 3 typescript, vue mastery, vue.js, vue.js tutorial, vuejs
Id: l12xx0N46KY
Channel Id: undefined
Length: 30min 15sec (1815 seconds)
Published: Fri Jun 11 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.