NuxtJS data, asyncData, fetch and nuxtServerInit - when, how, why?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys so today I wanted to make a video about a little bit of a smaller part of Max Jes because I've noticed when I've moved over from puja as to max Jas which view Jas is built into NOx J's but Knox is a server-side rendered version of UJS pulled by Aleksandr Chopin I think correct me if I'm wrong and I'm sorry if I'm wrong but so what I've noticed is when I moved over from view to Knox the one thing that confused me quite a little quite a bit was the difference between data async data fetch and NOx serve in it and I don't mean speech as in the web api fetch I mean the method fetch on the next object so today I'm gonna go through this a little bit and what I understand from it in case you got stuck understanding this this is how I made sense of it first of all let's just recap what NOx works like I'm pretty sure a lot of you already know this but next is a server-side rendered version of you so basically we make a request to the server we have access to request response store if we use specific methods and then we can pre render the data or we can use a static bolt as well but this video is going to focus on pre-rendering the data on the server and then sending it to the client so the data property is a synchronous data property with what that means is we can set the data property and it will run on the server and the client but it it's limited to static data and that is kind of the the whole the whole back of data usually what we want is maybe to make a request to an API and then populate data with that and then send back the file to the client and to do that we use a sin theta so async that is similar to data it has a server-side version and a client-side version but if we set the if we set it on the client side I mean if we sit on the world server side then we can do stuff like a sing Kronus requests and in public data before the document gets sent back which we can't do in data so with Fitch which is not the Web API but the fetch method within Knox it's kind of the same except we don't set the data on the server with the asynchronous method we set the date or we do set the data but not on the page or the component or the layout we set the data within the store so this does not give us access to the data that is in the client itself on the page itself not the client but the page or component or layout so with async data we set this data on the server and when it comes to the client we can access it with this data with fetch we set it on the server but we have to access it through the store if we set it on the store or whatever so it's basically just meant to run something before rendering your page doesn't have to be a store thing but just to make sure that you do something before the page gets sent back Knox server in it works a lot like fetch except its purpose is to be a store action so this is an action that calls itself when the server initializes and then we make a request to the server the action runs and you know it could be asynchronous and pop to a mutation set the state and then when that's done we can send back the prerendered stuff with the store data and we have access to that data in the store as well so it also doesn't include data on the on a page or component it it has to do with the store itself so enough talking let's look at some demos so what I've done is I just created a small little view application the folder structure is or Knox the application excuse me the folder structure is the base structure that comes with Knox with the store and the pages the components layouts all the normal stuff if you want to see how to set this up go check out one of my other Knox tutorials are always start from scratch but today I just decided to pre do all the template and script and stuff just so we can work with data so let me just explain what's going on here the index page so the home page has a list container that has a list item component and this list item is looping and it's getting a title prop and the title we're setting from the titles in the data property the normal data not a sync data so if you go to components we can see that we receive this prop and the default fallback is just fall back we see that the default string is fall back so if we open up a browser on localhost 3000 then we should see that the application renders our list so we have like one title to title three and if you noticed I have sorry I'm just rearranging this stuff if you notice I have set a console that log in created so if we look at the server the the logs within your command line tool will be on the server so it does lock the data we have our title 1 title 2 type 3 if we look at the client we'll see that we have an array of 1 2 3 so next SS all logs is also the logs that happen on the server it just gets sent through to the client so we have access to this data but let's say we want to make a request to an API and set this data how would we do that we can't do asynchronous stuff within data it has to be an object that has a property of titles and then the those titles will be an array so what if we do a created and then set this data to data that is one way of making a request and then sending it to data but we there's an easier way to do that we can simply do it once on the server and then it will be available on both sides so we can emulate that by just saying async data and then this will be a function like that and then we can return [Music] an object with these titles save that and there we have our titles so now we removed or created but if we log it'll still be the same console that log the subtitles but this isn't really the use case for acing theta because we want to do asynchronous stuff so let's do a JSON placeholder there's a API that it has like a fake race thing so I'm just gonna use this end point that they have and it's basically just fake posts and I'm gonna add it to our component so I'm gonna say let URL equals that thing and then in async data we can say async which makes this an async function now and then we can do constant response equals await and because we are waiting this next we'll know that it shouldn't rain that it shouldn't send back the response before this is done so we'll say await the the pitch of that URL and this which is the pitch API but this isn't a browser environment and I'm not sure if pitch will work so let's be safe and use Knox's next Axios module did we install it yes we do have Axios available so you can just install it when you run next NP x period Knox that so I'm going to say but then that won't be response yeah and we can say this dot dollar sign Axio start get the URL and then we can say con stata equals response dot data and then we can return but the data comes as an array of posts so what we want to do is just a constant I tells equals theta dot map which is a built-in function in JavaScript and then the callback has a post and we only want the post title so we can D structure this and just say the title property within post and then what we want to return is just that string title and that will give us an array of string titles so now what we can do is return an object with titles sailors titles save that and see what happens three load cannot read property axioms of this oh that's true because this is not accessible on the server-side so we have to import Axios so we can do Const Axios equals require Axios and then we can just do Axios get save that reload and there we have them we have all of our posts being set from the server and we can check that we can make sure that that is what what's happening by checking this and there we go we have all of these arrays posts let's check if there's any areas no errors and you can see the same log from the noxious SSR logs so that that means that we can do asynchronous stuff on the server side before rendering the page and we can even change we can change this when it accesses the page so let's do mount it which will only run on the client side we can console that log process client and then you can reload this check this out and true so that means we're only on the client side now so what we want to do is when we on the client side we want to say list of titles dot equals an empty array so it reloads on the server and then when it gets to the client it will be and we can before we do that we can check and create it if it has been created so created which will run on the server first we can log our posts so console that log list of titles so if we reload this page we can see our posts log and as soon as it gets mounted you'll even see a little flash of all our posts but as soon as it gets mounted we have access to this dot titles which is very cool so we are working with the server-side stuff and the client side stuff with one little property ok so now let's have a look at fetch what fetch we'll do is we'll use it to populate the store so let's first create a store and in Knox the credits all you have to export the stores different keys so we can do a constant state and this has to be a function because a function that returns an object and we can do titles will be an empty array and then we can do and we have to export this for this to work so we can do export and then you can say contact or first mutations we have to use mutations to set our state we have to export this and we can say set titles remove this set titles we'll take a state and a payload and what it will do is it will say state dot titles or equal the payload basically mutating our state so now let's look at the fetch API we don't need the actions yet we'll use that when we do not serve in it but first let's look at the fetch thing so now we still have async data as to do our titles but instead of this let's remove that and let up here let's first import our store our map action map state helper so we can do upstate from UX and this is just a way to short shorten our syntax so what this does is it just accesses this that's stored out state that whatever you want to access in a shorthand way so what we want to do is look at Fitch so now let's set a sync Fitch and this receives a context so this context is actually available within all these async data and Fitch not serving it they all receive a context item and we can go look at that that by going to Knox context and then in the context you'll see that we have access to our app to the store to the current route to parameters the query and this is in both client and server side on the server side we have implicit access to request response and before not surrender and then on the client side we have from which means where is this current route coming from and the current next state which is a very special state that we can sit but that's also a topic for another video so we'll do well we want to use the store so instead of saying context we can just D structure the store from there and then what we want to do is say store.com it set titles and then we want to give it that array of titles so let's give it one two and three save that and now to use that we have to use our computed property and then we want to say dot dot dot map state and this takes an array of names and we're just mapping the title so what this is doing under the hood is just saying it's creating a function like quotes titles and then it's saying return this dot store dot state titles so that's what that's all that that's doing and then save that and there we have our titles and this is also being set on the server side so let's do console dot log process dot server and then inspect this oh we have an error you won't prompt omit the titles not to find an instance but reference during the render dum-dum-dum okay so that was just an error I don't know where that came from so let's reload this page and then we have true because we are on the server when we do that and we don't have with this next log comes from the server so this commit is happening on the server before we send back the page so that means everything is ready to go and we can do all sorts of asynchronous stuff so what an asynchronous thing because we do to say async now so what we want to do is again just do cons response equals await Axios dot get the URL and then cons data equals the response data and then cons titles equals take that map and we want to get that title property and then just return that title property when we return that it creates an array for us so now what we want to do instead of one two three we want to set it to that array of titles say and there we have a lot titles again rendered on the server sent to the client compared to acing data that seems pretty much the same but if we didn't have this computed thing and we save then we wouldn't see our titles because Fitch does not set the doesn't matter what we return if we if we say return titles and we say that it's not like the async data method that sets titles you can see public meta titles not defined but if we return titles in the async data then we will have it available so that is the key difference between those two we have to do something in fetch and we still need to get our data from the store ok so next up and finally we can look at next server in it a lot like fetch except it happens in the store so we it's an action that runs by itself when the server initializes whoops and actions name is next server in it which also receives that context but first it receives the context of the store so we want to give it to commit there's the so be the this will be that store context we have store commit whatever so we can give it a commit yeah and then in this in this context will use request or response or whatever so we'll just use commit and then what we want to do is all the things that we did here we can remove Axios from here and the reason why we would use Knox server in it instead of fetch is to basically have this run for the entire application and not a specific page so if we use fetch we can use as something on that page or which is specific to that page to set the store or something like that but not serve and it runs in the store and makes it available to the entire application so you would want to see your applications in so data from this maybe by doing this request so we can do all of this and put it in here because if we for example want this data to be available this titles data in all our components that means every single component when it's fetched I mean every single page when it's fetch needs to run this async fetch method and instead of doing it over and over we can just do it once let's say that we can get our URL because we need that as well and we can get our map state we need we need this we need that save that and now we can look at our actions which needs to be async and then we can commit state titles and there we have it so that's not serving it is doing the same thing as fetch it's setting the store but from the global store so it doesn't matter what page we do map State on we'll have access to the titles because as soon as the application is generated or started the store action runs whereas if it was just in the index or in the list items component or whatever so you might want to break down your API request into smaller data chunks so you'll just do a fetch from this component that fetches maybe one item based on the request the request so we could do just to try something quickly we can do async which and then instead of or we can do a sync date or rather because we only want to access it in this page async data and then we have in the context we have that store and we have that params so something we could do here is we could say if store dot state dot user because remember we don't have access to this so we have to be use the store like that so if store dot state that user returned some object return may be logged in as false and then we can do if no stored of theta theta yeah we can actually just do return login that's true so that is an opt that is some pattern that we could use so we check with a sync data and we can use this route params as well so if we make a request for a specific ID or something we can say if params dot ID equals the page dot ID or something like that some data property that you said then you can dynamically render some sort of data on the server before sending it back like in the case of this if there is a user we don't have to say like in the menu bar login because he's already logged in if there's no use in the minibar we can say don't login you know and this is rendered on the server side instead of having to so we can do a fetch we can do a fetch for to our API server and say fetch user and then if you use a all those kinds of thing because we have async date and available to us and we don't need to do that in any other component except if this was like the earth component we wouldn't need to do that in the store so that's why there's different context in which you use all these different ways of getting this data and setting it yeah so it's a very simple example but I hope I got the differences through so just to recap on the page we could either have we can have one of three things we can add data we can have async theta and we can have fetch so data is synchronous and it is available on both client and server but you can't fetch something from another API or something like that it it has to be synchronous it has to be static data async data can use pitch etc and then which doesn't make data just lets you run code before client something like that so that's the difference between those three and then in index the NOC seven it would be just like fetch except in store and it runs by itself so you don't have to call this function or anything like that it just runs on the server so I hope this helps someone out or made some sense to you guys it's a short one today I am planning on making a course a free course on YouTube because I'm graduating soon and I'll have a bit of extra time but I want to make a free course on web development in general and release videos weekly or bi-weekly for complete complete beginners I know my videos have been targeting a little bit more intermediate type folks or but better than beginner because you know it's it's based on frameworks and stuff but what do you think about creating a beginner course for free from scratch from zero knowledge to being able to create a website and put it on a server and understand what's going on yeah let me know in the comment section what you think do you like the video please give us a like and thank you for watching channel is growing slowly but surely and I really appreciate it guys I'll see you in the next video peace [Music]
Info
Channel: Kaizen Codes
Views: 18,851
Rating: 4.9385967 out of 5
Keywords: Web development, Software, Javascript, Coding, NuxtJS data, asyncData, fetch and nuxtServerInit - when, how, why?, nuxt, nuxt data, nuxt asyncData, nuxtServerInit, nuxt fetch, datain Nuxt, server-seide data nuxt, nuxt ssr, nuxt vuex, nuxt store, Nuxt models, Nuxt server, Nuxt client, Vuejs data, Vue data, Vue computed
Id: NDVCquHbFIM
Channel Id: undefined
Length: 26min 0sec (1560 seconds)
Published: Fri Oct 04 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.