Vue API calls with Axios

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi i'm greg pollock and in this lesson we're going to be talking about api calls with axios we'll be looking into why we need to use axios inside view how to install it how to make api calls with it we'll talk about the component lifecycle and when to make api calls and then we'll encapsulate our api calls into a service to keep our code more modular in our example app our view application directory structure looks something like this when we go to deploy this we'll write npm run build this builds our view application into the dst directory and gives us the files that we would then deploy onto a server then when a browser requests our website it serves up the index.html file and loads our application which right now looks something like this however the event data we're loading onto this page is getting loaded locally from inside our event card dot view file in a real world application this is where our api is usually called first our application gets loaded in the browser and then it makes an api call to our server requesting api events for example and this returns a json response which our view application then displays on the web page vue doesn't have a built-in way to do api calls why because javascript has a lot of great libraries to do so the most popular one to use in view is called axios the axios javascript library allows us to do get post put and delete requests add authentication on each request set timeouts if requests take too long configure defaults for every request which we'll be doing later intercept requests to create middleware handle errors and cancel requests and properly serialize and to serialize requests and responses and if you really hate it when people read bullet points to you i don't blame you this slide was a little painful sorry won't happen again the very basic get request using axios looks something like this here we are doing a get request to this url then when the response returns we're going to log it to the console and we'll catch and log any errors that get received it's important to note that axios calls run asynchronously which means that the code doesn't wait to be completed before continuing let me show you an example if i wrap this in an api call logging out enter at the beginning and i log out exit at the end of this function when i run this function on the console i get enter then i get exit and at some point in time when the response returns it'll log it out to the console showing how our axios call doesn't wait to finish before the code continues executing our next goal for this lesson is to load in events using an api so it looks something like this to do this we'll need to mock a dummy api server we can call we'll then install the axios library we'll build the api call inside a component using axios we'll then use the returned event data in our component to display it and lastly we'll reorganize our code into a service to make it modular before we create our fake api i want to note that there's different ways to create api servers they can be built with frameworks such as express.js which uses javascript laravel which uses php rails which uses ruby or even django which uses python we can also build our api using a service such as firebase or parse or even ones like graph cool which allow us to use graphql to write queries now we're going to jump back into our example application and start mocking our api i encourage you to follow along if you're coding along with us and if you're just joining us you can look in the lesson resources and download the starting code also in the lesson resources you'll find a db.json file which you'll want to download and put in your root directory this contains a json object which as you can see has an array of events this is what we'll want to serve up using a mock server which we'll do by installing the json server library using npm once it's installed we can run json server and specify this db.json file this runs an api server at localhost 3000 and when we go to slash events it serves up our events array next we need to install axios which we'll do from the view cli user interface to run the user interface we need to run from the command line view ui then if we go to localhost 8000 we'll see that we can click on dependencies we'll click on install dependency and then search for the axios library selecting it and clicking install axios now back on our dependency list we can see that axios was properly installed as a side note it's important to keep your view libraries up to date and i noticed when i came in here for the first time that our project plugins are out of date the cli service for example has an older version installed the latest being 3.0.1 so i'm going to go ahead and update that i can do so by clicking this update button on the right hand side if i want to see what's going on under the hood i can always check back on the cli console now i can see that got updated if i want to update all plugins i can click on this button here also when i click on dependencies some of my dependencies are out of date i can update those as well by clicking update dependencies these things can be done easily from the user interface but also from the command line so here inside of our editor we can run npm outdated and we can see a list of all the outdated packages to update them we can specify a single package to update by just writing npm update and then that package name or we can simply write npm update and then it's going to update everything now running npm outdated nothing gets returned we're all up to date to install axios from here if that's how we chose to do it we could just run npm install axios you don't have to use both ways just use one of the other i thought i would show you both now that we have the axios library available to our project let's start using it to make an api call first we're going to go inside of our views directory and open up our event list we'll import the axios library here we'll make our api call inside of the created lifecycle hook see your view instance has several methods that you can call to execute code at different points in the component life cycle in this diagram here in the documentation you can see we have before create create before mount mounted before update updated before destroy we want to call our api inside the created lifecycle hook so here we'll call axios we'll make a get request to the mock api we created then when a response is returned for now we'll simply log out this response to the console we also want to catch any errors that are returned logging those out to the console as well we need to make sure our server is running it's not yet so we'll run npm run serve and if we go inside of our browser we will open up devtools it logged out each one of our events that we received from the json server now let's use this event data inside of our component first we're going to specify a data function because we want a reactive property called events which will start out as an empty array then when our api gets returned we'll set this.events equal to the response data now we need to iterate through each of the events that gets returned from our api we'll say v4 equals event in our events array specifying the key equal to the id of that event and then we need to send in each of the events that we're iterating through as a prop to our event card component now inside of our event card component you'll see there's our locally loaded data that we're statically loading onto the page we'll delete that because this now needs to accept a prop called event which is an object that's all we need to do if we go into our browser we can see it's properly loading data from the api onto our web page but if we click on event listings we'll see huh it's only loading event slash one even when we're clicking on an event with id of three so what's happening here if we look back in our event card we'll notice inside of our router link ah we have hard-coded the id of one so instead this simply should be event dot id now if we go back into our browser when we click on an event it properly loads that events id before we move on and actually implement that event show page we need to reorganize our code a little bit see right now our event list has an axios call in a minute we're going to create another axios call inside event show there's two problems with this the first is that each component is creating its own axios instance and our browser only needs one the second is that our api code is about to be in two different places in our application which is going to make things harder to debug it'd be nice if our axios code was all in one place so we're going to take our axios code and we're going to move that inside of a file called event service.js our components when they need to make api calls will call functions inside of event service let's jump back inside our example app inside of our source directory we're going to create a new folder called services then inside that folder we'll create a new file called eventservice.js this is going to import axios then we'll create a single axios instance like you see here that's the single axios instance for our entire app we'll then have a base url that all calls are going to use which we'll use in a minute followed by any authentication and configuration that our api calls need to communicate with our server then we'll create a get events function which uses this api client to get slash events because we have a base url this get request is going to call localhost 3000 slash events because we specified a base url now to call our event service we're going to go into our event list inside here instead of importing axios we'll import our new service inside of our created lifecycle hook we now simply use this service calling get events that's all we need to do now if we go back into our browser everything is still working but our code now is a little more modular and maintainable next let's add another api call when we show an event first we'll go into our event service and we'll add a new call we'll call it get event it'll receive an id so we can tell our api server which event to fetch now inside events show we need to import our service specify a new reactive property called event which starts out as an empty object then inside our created lifecycle hook we'll call our service sending in the event id when it responds we'll set our data equal to our event and we'll catch any errors that happen simply logging them out to the console lastly let's print out just for now the title of the event that's retrieved if we jump into our browser we can see yep it's properly fetching the name of this event using our api let's go ahead and paste in some template code you can fetch this yourself from the lesson resources so that's just printing out more information about the event displaying our properties using dot notation then at the bottom i'll go ahead and paste in some styling now you can see we're printing out a lot of different information about our specific event if you're following along you might have noticed that when we loaded our event show page we got a console error it reads cannot read property length of undefined we're calling the length function on an undefined property and if we look into our code it's happening right here this is because event dot attendees starts out as null before it gets loaded from the api to fix this we need to add a ternary conditional so here if attendees is not null we can run length on it otherwise just return zero and now if we go back into our browser and refresh we can see that our error has disappeared i know that was a lot so let's review we started the lesson by talking about why we need the axios library to do api calls from insider application we talked about how to install it and then how to make api calls from insider components we then briefly talked about the component life cycle which i recommend you read through the view documentation on the subject by clicking the link inside the lesson resources lastly we talked about creating services to encapsulate our api calls to keep our code more modular and therefore more scalable congratulations on reaching the end of real world view to continue on your path to view mastery the next step is to take our mastering view x course see you there we come on my god something's going on just when you think it's done [Music] all right i don't even know where i was
Info
Channel: Application Development
Views: 6,172
Rating: undefined out of 5
Keywords:
Id: xexLEiwJrnA
Channel Id: undefined
Length: 17min 52sec (1072 seconds)
Published: Sun May 30 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.