Vue 3 Fundamentals

Vue 3 Fundamentals Fetching Data in Lifecycle Exercise

Learning Paths:
Check out a free preview of the full Vue 3 Fundamentals course:
The "Fetching Data in Lifecycle Exercise" Lesson is part of the full, Vue 3 Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:

Students are instructed to create a UsersPage component, leverage the created lifecycle hook to fetch a list of users from the JSONPlaceholder API, and render the returned list of users to the page. Ben then walks through the solution to the fetching data in lifecycle exercise.

Get Unlimited Access Now

Transcript from the "Fetching Data in Lifecycle Exercise" Lesson

>> Okay, so for the exercise we're actually gonna be using one of my new favorite APIs called JSON Placeholder. If you haven't heard about it, it's pretty great. Because what it does is it basically provides a bunch of static data that requires no authentication key or anything. And what allows you to do is it has a bunch of different datasets that allow you to relate between them.

[00:00:21] So basically we'll see here, we take a look at users, for example. Users has an ID, it has all this data ready for you. But then if you take a look at something like the dodos, you'll notice that it even has user ID and it relates back to those users.

[00:00:35] And so what you basically have is, rather than having like a dynamic database that oftentimes goes like either unmaintained or eventually goes out of service this is really just a bunch of static JSON, but we get to request it as if it were from the back end. And so this is the API that I recommend you all use going forward when it comes to our exercises.

[00:00:58] And so for our exercise, you're gonna be using the C'est La Vue app, and this time your product manager has come to you and says we need a UsersPage component, right? So we're gonna give you some practice as far as basically go ahead and create the user page inside the component folder.

[00:01:13] And then inside of that component, go ahead and use that created lifecycle to go ahead and fetch all the users from that JSON placeholder API using what we just showed you. And then go ahead and render that however you see fit. And then go ahead and make sure you update App.vue so that If you wanna use a dynamic component, that actually swaps it out correctly when you're using the navigation.

[00:01:35] Welcome back everybody, how was the exercise? All right, yeah, it looks like people were successful. So no worries, in case you find that a little bit complicated, we're gonna walk through the solution right now. So let's go ahead and do this. So let me close that. Bring that over here.

[00:01:55] As you noted, I do want this as a reference? I'm gonna bring this as a new tab, okay. All right. So I'm gonna go ahead and I'm gonna work in the C'est La vue. Remember that If you are working in your app you can go ahead and use whatever I'm doing in C'est La vue as like an example for how the solution should look in your app.

[00:02:16] Okay, so I'm gonna go and check out the -09 branch solution so that's where this will live Okay, so first thing first, what do we wanna do? We wanna create a user page, all right? So we're gonna do inside of our components folder UserPage.vue. And then I'm gonna go ahead, and let's set up the script block, and let's set up the style block.

[00:02:39] And so taking a look at what we have here, we have some basic styles. And so for now, I'm just gonna kind of keep it straightforward in the sense that like, let's just go ahead and pull what we already have. So I'm gonna actually grab, I think the login page is fine for me.

[00:02:54] So I'm gonna go ahead and actually not see doo doo doo doo. Yeah, I'll describe the login page. Okay, so I'll grab the login page copied over into our user page for now. And I'm gonna actually delete these or I'll leave them because they'll actually be a great discussion point for later.

[00:03:09] And for now, we'll just call this users will delete this stuff. And we'll just save. So now if we go back we're on the homepage. We won't be able to see this yet, why? Because we actually need to update our App.vue so that we actually show that page.

[00:03:26] And so for now, we're just gonna make it easy. And we're just gonna say, okay, well, by default, we're just gonna show the UserPage. But we wanna show the User Page. What do we got to do? We got to import it because we're actually gonna call that component.

[00:03:40] So that way we call it, we register it, that way it can actually be called later on. So if we save that and refresh, nothing is working. Why is that? Well, we need local dev running. Let me close that one. Great, there we go. Okay, so we have a User Page up and running, looking good.

[00:03:57] And so what do we wanna do? We wanna go ahead and fetch our users from this API right here. So following our best practices, we'll do the export default object and inside of our created, we're actually gonna go ahead and run a function, what are we wanna run?

[00:04:11] Ideally, we want something like this.fetchUsers. But we haven't written that. So let's go ahead and write that. So I'll create a methods here. And the methods option will contain the fetch users. Inside of here, this is where we're gonna go ahead and run our request. So we might have this.userList equals what?

[00:04:31] We're gonna fetch this API and then we're gonna take that response. And then we're gonna JSON-ify it by running response.json. Now again, this is an asynchronous request. So we need the await keyword, and we need to tell it that it's async. Not quite done yet though, because why?

[00:04:48] We have this this userList hasn't been created yet. This is our reactive data. So we can go ahead and create that. And so we have our userList and that will be an array. And then we can save. All right, everything formats, it looks good. That code editor is not yelling at us anymore.

[00:05:09] And so we aren't seeing anything yet, and that's totally fine because why we haven't actually rendered it to the screen. So userList. There we go. We save and we refresh. Okay, now that we do it great, we can actually see all our users here, but we're gonna go ahead and pretty that up a little bit because that is pretty hard to read.

[00:05:26] So I'm just gonna do an unordered list. And for every one of these users, so user in userList, we're gonna make sure, because we're using a V for loop, we're gonna assign it a unique key. And that key can be just be the ID actually that we have up here.

[00:05:41] So I'm gonna actually gonna say, doo, doo, doo, I'm gonna use the ES6 templating though, to say user And the reason for this is, because this dataset is on the simpler side as far as keeping the IDs as just numbers. And so I do know in advance that there will be other elements that also have very simplistic IDs.

[00:06:01] And so prevent that from colliding, cuz when it does vue will tell you inside of the console log, hey by the way I'm seeing duplicate keys for elements and that will create all sorts of havoc for you. So try to keep them unique whenever you can. Again, normally these will be U IDs and you don't have to worry about it.

[00:06:18] And then we can basically render out the and then let's go ahead and let's just do the, what would be fun to do? Let's do the website then. And then we have Save. There we go. And we can see now if we refresh. Okay, we got a lot going on.

[00:06:35] Now for a second here, I panic because I was like, why are we seeing double? The reason we're seeing double is because we have the pre-elements there, so we save that now and refresh. There we go, much better. And now we have all our users being rendered on the page.

>> Is there a way with the dev tools to see the unique IDs of those items?
>> Yeah, that's a great question. So if we take a look at what the context here is, is that this dynamic key that we're assigning in this case, user-1, and so forth.

[00:07:03] The question here is around the idea if there is any way to expose that. And so honestly, off the top of my head we can see here that if we're looking at the browser dev tools, there's nothing actually indicating what the keys are. And if we take a look at vue dev tools, we can see here that one nice thing about dev tools is that it makes it very clear how you can expose the different properties of it.

[00:07:22] But it does look like at first glance, there's nothing obvious kind of indicating its individual keys, like we can inspect the elements in here and all the data in here. So in case you ever debugging anything. And a nice little bonus about this too actually is that the dev tool allows you to modify directly.

[00:07:40] So we come in here and just call like, like Selena as a middle name, you'll see that will actually update it directly. So it allows for a kind of a quicker feedback loop in case you're wondering like if your dataset is doing something specific with your code. You just play around with it right there rather than like, call it going back to your component and faking the dataset, like the dev tools allows you to kind of do that in In a centralized way.

[00:08:01] I wonder, can I do key="renderPage" like that? Okay, great. So I did discover this at the bare minimum through this exercise. If you provide keys to your components, these are showing up in your dev tools. So there's something to be said, where if you're at the point where you're probably debugging keys, at least for your components, it probably is helpful to, I mean, to be honest, if we're thinking about like a real world scenario, the user page would be displaying probably a user card component, and then those who should show those.

[00:08:40] And so for the sake of actually demoing that because this is actually something that does occur in apps. So let's do a UserCard real quick. And then I'm just gonna go ahead and drop that. We're gonna drop this li, we're gonna keep it simple. We're just gonna assume all user cards are always list elements.

[00:08:58] And then I'm not gonna worry about that piece. [COUGH] And then we're gonna go ahead and quickly just define a prop. Default props and they'll get a user type of object and required is true. Save. And then inside of UserPage now, we can actually import set UserCard. And then there we go.

[00:09:23] Just use the autocomplete for that. And then the components. There we go. And then dropping UserCard in here. And then we can then say UserCard is what we're gonna use here. We're not worry about that. And then we're just gonna make sure we pass user inside of here.

[00:09:46] Like that. That should self close, save, okay. That should do the trick. It looks like everything's working. And to validate this real quick, what we're gonna do is we're gonna add a quick CSS class called user.card. And I'm just gonna say user.card has border 2px solid. Let's keep it simple, let's just do like a black and then just like a padding of 10 pixels.

[00:10:18] There we go, okay. So our cards are rendering, we have our user page here rendering our list of cards, which looks good. And now we go ahead and open the dev tools. We should see, what I think I saw a glimpse of that a second ago. There we go.

[00:10:31] The keys are showing up in this case. So it does look like if you wanna inspect the DOM element one that remains to be a little bit elusive. But that said, it's still a worthy question worth investigating into.
>> On the topic of keys, are those keys, do they need to be unique on globally all items rendered on page, or is it kinda scoped to the component?

[00:10:54] So if your component renders one list, is it safe to just use key 1, 2, 3, 4?
>> Yep. Sorry, the yep was acknowledging the question. Okay. So, to the question here is around the scoping of keys, right? Because we talked about scoping of data, right? Data scoped to the components, and we have to be very explicit about how it's shared.

[00:11:11] Keys however, are different because it has to do with whatever's on the page. So there's no scoping in regards to keys. And this is very important in particular when it comes to animation and transitions. This is because if you want vue to start managing some of those pieces those keys do really need to be unique otherwise you'll start seeing weird glitches of like vue trying to calculate how to move things around and like two or three things at once.

[00:11:32] And so yeah, I would treat keys as a universal thing. This is why knowing the dataset that I have, let me close this. Knowing the dataset that I have that is why I prefix that with user so that later we can have like photos or comments or whatever whatever we decide to extend upon.

[00:11:49] So, good question though. Cool. So, we have the ability to go back here to home and log in, but we don't have a user link. So let's actually just make sure we wrap that up properly. So for now, we're just gonna keep it simple here. You might notice though, when you're inspecting the nav that I'm doing something a little bit hacky.

[00:12:07] One is that this is technically an anchor link, but the anchor link doesn't go anywhere. It only goes to the top of the page. But on the click event, you'll notice that I'm adding this modifier.prevent. If you're not familiar with this, think of it like a form. Form is the one where I typically show off the prevent.

[00:12:23] And so what happens a lot of times when you have forms on an HTML page. You wanna actually stop the event from submitting and then do some stuff before you submit it. And so typically what do you have to do, if you had a submit form that was like submitRegistration.

[00:12:36] Inside of your submitRegistration function you'd have to do run what, you have to get the event. You have to run event.prevent default. Well, vue was like wait, we do this so often, why is that code polluting really logic that's separate from it. That's really just basically a logistical implementation.

[00:12:51] So by adding .prevent to your submit, it automatically basically executes on that prevent default event so that your code can be cleaner and you don't have to worry about, basically it's easier to modularize things. Because otherwise your functions have always this context of being attached to an event which might not always be true.

[00:13:08] So this is kind of some syntactic sugar that's useful that's being used. And so in this case I'm using click.prevent to prevent it from actually doing the navigation. Again, to be very clear, this is hacky because, right, we are gonna get into official routing and so we can change URLs and those sort of things.

[00:13:24] But for the sake of practice right now, this is why we have it. All right. That said, we have an href. Again following just the same model click.prevent. And this time we're gonna showUserPage. User, that looks good. And then here showUserPage. this.currentPage equals User, okay. Okay, that looks good.