Learn About SvelteKit API Routes And Server-Side Rendering Pages

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey friends in this part of the swellkit series we're going to be learning how to create API endpoints and loading data for pages in swellkit so here I have a simple selfie project which were at this point you already should know how to make and I just have some default Styles so you can go to your app HTML and here I have included some Pico CSS Styles which you can include yourself if you want and then I have some Global Styles which is apps.css and then I just have a root layout here where I'm importing the Styles and I have some basic navigation here and that's basically it if you want to catch up and you don't have this project set up and here is nothing special just say hello and then you can go and run the development server so I can say pnpm run Dev and now we can go to 5173 and everything should look great before I get started I'm going to set up a database with Prisma and Prisma is really awesome because it basically instead writing raw SQL you're going to write something more that looks like typescript and this is a schema in Prisma which you can look at this example here here is how you define a table in your database you can just say model post and Etc and this is really simpler than writing raw SQL yourself for database I'm going to use sqlite which is really awesome because you don't have to set up anything it's just a file on your system meaning you don't have to figure out for an hour how to set up a database or sign up for things you really don't care about and I'm also going to show you how to see your database we're going to use some placeholder data from dummy Json so here it has 30 posts for us by default when you open the API so we can look here here are the posts so we're going to input that into our database just so we have some data to work with but yeah let me close this and let's get started so I can go here I can press Ctrl C to stop our development server Ctrl fail to clear everything now let's start and initialize the Prisma database so I can save pnpx Prisma init and this is mostly just going to be a speech run how to set up Prisma so we can use data source provider this is really an awesome and quick way to set up sqlite with Prisma providing this flag so you can just say enter and this should take a second and if you look here what happened this created a Prisma folder with our schema so you can really ignore this part to the top we're going to write our schema here and also created a EnV file let me just close the sidebar so you can see what's going on and here is the beautiful part about Prisma so this connection string here you can replace this with anything later you can create a database on Super Bass for free right you can just drop in the connection string here and you don't have to change anything else Prisma supports many databases from poster SQL SQL to even mongodb I think but before we get to writing our schema we also need to install the Prisma client which is going to let us interface with the database so I'm going to say pnpm I we can say Prisma client and I'll give it a second awesome so now let's create our schema so I'm going to close the terminal let's close this and how we can start creating our model here and model just means table model post and I'm going to give it an ID and also if you want this Auto completion you can get the Prisma extension from vs code but you don't have to so we can just say int which is a built-in type ID is also built in and also you can see how you get this great Auto completion thanks to typescript we can just say Auto increment and of course we're going to make this up I just took this from the Prisma example which also had this created at timestamp which is a built-in date type time we can say default now so that's how simple that is we also might want to know when it's updated again we can use the same thing but here is a special updated ad and now we can create our own fields so we can go here and basically this is really intuitive you're like okay title is text what is text in Prisma it's string of course and now we can just say content or body string and if we give it a question mark it's optional because you might want to create an empty pose which is fine for this lock we want to beat unique so you can just say string and we can also make it unique using this so we can look this up using Prisma which is going to be really simple and then we can also have a publish here so this is going to be a Boolean simple as that and we also can give it a default value which is really awesome so you can just say false and now we don't really need to even think about this field and now when I'm going to save Prisma is going to format this file but before we create the database let's create a seed file so we're not going to need this schema anymore we can close this let's go to Prisma I'm going to say new file seed TS you can say import Prisma client issued autocomplete for us very nice we can say cons DB new Prisma client and now we're going to create a type post which is going to be matching the post from the dummy Json response so you can just say title string body string and we can open it here on the side so you can see here open which is awesome so as you can see here it returns an object with a post array and this has for every post ID title body we don't really care about ID we're going to create this ourselves and these are the things we don't care about and that's why I only created this type for title in body so you get great total completion alright so now let's fetch this pose so we basically let's copy this URL because we're going to need it we can say async function get pose and now I can say const response await Fetch and now I can just copy over this URL and now we can the structure pose because this is what it Returns on the object right close post from a weight response Json and now we're going to return the pose and if I save this you can see one problem here is the difference promise any so we don't really get the type back that's why we created this type so in typescript we can say s post but this is just a single post we have to say hey this is an array of posts awesome and now if you hover already as you can see it returns a promise which is of type post as an array so that's really not complicated and I'm also going to create another function that's going to be slugify so as you can see here this is this long title and I want to create slugs from our post title which would be really convenient if the API head is but it doesn't so you have to do it ourselves you're not really need to import any other library because it's really simple to create such a function so you can say function slugify it's going to take in some text which is going to be a string and it's going to return that text let me just make this easier to read so we can just say text replace and now we can give it some regex and then we can also Define what it needs to replace so you do it like this and you say Global so it's going to take into account everything and now we need to Target y space so we can say this so this is going to Target every white space and now what we want to replace it if you can replace it with banana or whatever but let's just say we want a dash and next we want to remove any characters that are not letters numbers and Etc so this can be punctuation some special symbols or whatever and you can chain this you can say replace and now we can also specify our regex and let's just say we want to replace it with nothing so let's start writing the regex here we can do this matching thing so we're going to match a lowercase to Z a uppercase to uppercase Z and then we also want to match any numbers but of course this really isn't what we want we want the opposite of this we want to match anything that is in this so how do you do that you can specify it using a carrot symbol you can do this and now this means hey I'm going to match anything thing that isn't here and also for the last part we're going to say to lowercase because we want to slog in lowercase and let me just show you how this works so I can get this part and I'm going to go here I'm just going to open the developer tools and let me just clear this and this is complaining because you really have the developer server so actually this is really annoying let's just go here and let's go to the console and now I'm going to copy over this call so of course let's give it some text so you can see and now this should create a slug so you can see it should replace this and it should fill in the dashes here so if I press enter and good thing that we don't do because we made a mistake and this is why regex is so tricky so you can see here we need to preserve the dash right so we also need to say Dash here and this should work so we can see it's Sami Mario okay so let me just also give you another tip if you go to regexer you can actually learn how this thing works so if I take in this regex let me just paste this in and let's also just give it an example Sami Mario and you can see it's going to not only match it what you want right so you know it works but it's also going to give you a description so this is really a negated set and this is going to give you all the description here and maybe you can also sha GPT which would be really interesting right but yeah really that's a hot tip so we can just close this for now and let me just clear this I'm just going to close this so basically now we have the slogify and are we going to Loop over the post and add them to the database so I'm going to create a function async function main you can name this whatever you want because we're just going to run it so before we forget let's just invoke it so in the script runs it's going to run so now we can get the pulse we can say cons posts await get post and you can see we're also going to get the types here which is really awesome so let me just briefly show you how simple it is to add a post in Prisma so what we can do is we can say await DB post we can say create you can see how awesome this Auto completion is you don't really have to think about it or look at the documentation and now when we pass it here this this is why Tasker is so awesome because we can just say Ctrl spacebar and then we have our option you can say Okay select doesn't make sense here have only data so I can do that you can see here is an object and now you can also go deeper and I can press Ctrl spacebar again and you can see here is the awesome Auto completion for Prisma so you can see everything you can enter here but basically what we have to add is the title which is going to come from the post title and don't worry this is going to come from our Loop just want to focus on this so you can say content Paul's body and remember we have to use our slogify to create a slug so we can just say slugify post title and now we can create the loop and when I'm dealing with acing things like this I need to Loop over I honestly don't like using map because the code looks really ugly because you have to wrap it in promise all or whatever and it looks really ugly and for this reason I prefer something that's more readable and that's a four offload so you can just say four cons post of posts and I can just do this and now you can move the code here just like that and now we can see here we have Auto completion from post and you can even destructure this if you want since we have types you can see body title if you want to do that but I honestly prefer legibility when someone else is reading this code and basically that's everything it's not that bad right so you can just save it and now before we can run the C script we need to add the save script right so we can just go to package Json I press Ctrl p and now we're just going to create a Prisma script and again this isn't some magic knowledge this is just from reading the Prisma documentation they have a nice section but one thing that isn't nice is how they describe seating which isn't going to work in cell kit because we're using type module which is using native JavaScript module and this is going to work with TS node but here is a simple solution to that so you can just say Prisma following just like they have it in a documentation now we need a c script and here is the part that's just going to work like a magic so instead of using ts9 highly recommend it we're just going to say pnpx we're going to use the wheat node package which is going to transpile on the Fly the typescript file so you can just say Prisma we need to point it to the C script cpts and this is just going to work now we can run the migrate command which is going to create the database from the Prisma schema and run the seed script if it finds it so now we can open the terminal and I'm going to press Ctrl L to clear everything and now we can run pnpx Prisma migrate so it's Dev name and now you can give it any name you want this can be banana but I'm just going to stick to init as I show in their example so this is going to create the database from the schema and it's going to run the seed script so let's press enter and should take a second awesome so let's close the terminal so I can show you what happened and also close the seed file you won't ever have to look at it again so here it created the sqli database word which is really awesome and you can see here we created a migrations folder so every time you make a change to your database you're going to have a migration here so here's an init and here is the magic source so it creates the raw SQL code for you this is how Prisma works and it's really awesome so let me just close this and another way how you can confirm that everything works Prisma has a graphical user interface which you can use to check out your database which is called Prisma studio and it really gives me phpmyadmin Vibes which is really awesome so you can just say pnpx Prisma studio and it's going to open it in your browser and here are the posts but what you're going to most likely see if you open it for the first time you're going to see this view here are going to be older tables you can see here we have posts and now when you view post here is the timestamps updated add title we have the content and now we also have the slug oh but of course I made a blunder and I'm really glad this happened so I can show you how you can reset your database so remember how we corrected the mistake not packing Json in our C script I really forgot to enter the dash here right so literally small mistake but I'm going to delete this in because it's going to be awesome so let me just save this so what you can do of course is you can delete everything but you can also say here pnpx Prisma you can say migrate reset are you sure you want to delete this you can just say yes now we can delete the migration and I can press Ctrl L to clear everything and let's just do the migration again so you can say pnpx Prisma migrate so it was Dev name in it let's do this again awesome so let's run pnpx Prisma Studio which would open it in another tab so let's just close this and let's see if this works this time and also now you have our slugs one last thing we have to do is actually export the database for use in our circuit application so for now I'm just going to close Prisma Studio I'm going to close this API and let me just close this close the C file I'm going to collapse everything just so we know where we are right so you can go to source and here is a special folder we can create which is aliased in swelkit we can just say lib and now we can create a database TS file and inside our database file we're just going to do the same thing we did in the seed script we can say Prisma client from Prisma client in order to create the database again new Prisma client and adjust default export it also now you can use this anywhere in our app let's talk about API endpoints you probably used an API like dummy Json so for example if I go here and look at all the available endpoints I can see here is the products cards users and post endpoint I'm interested in and let's go to the post and what really happens here right so to understand this we need to open the developer tools so you can say control shift I and let's go to the network tab also make sure you disable cache and now when we reload the page you're going to see some junk which is not important but here's the important part what is actually returned here is the document post so you can see here the headers preview which is the Json that got back so here all the posts so this is basically what we can fetch and show or do whatever here is the raw response so if you go to the header here's the request URL the request method which is get the status code 200 okay but how does it know right that this is like Json and it should show it like this basically this is because of the response header so we can see the content type on the response header is set to application Json and also another thing is that you might not be seeing this like this and the reason is because I'm using an extension so if I go to extensions and this is true for all chromium based browsers which is really surprising to me that the current year chrome doesn't have this and Firefox had this for years so we can go to extensions you can get an extension like Json viewer so this is how it would look like for you if you don't have any extension let me just go here I'm going to refresh the page so you can see now that this matches the exact same raw response but basically we can just get an extension use Json viewer if you want but you can use anything else I'm just going to refresh it and also if you're curious you can go to the settings here and I'm using this Panda syntax theme so I can close this and this looks great alright but where am I going with this basically what I'm trying to say is that swellkit also makes creating API endpoints simple and in do that by creating a special plus dot server TS file that exports a function that corresponds to a HTTP verb which is get post patch boot delete or whatever else that function takes a request and returns a response and if you don't know about HTTP request methods where you learn about it of course on mdn so you can say HTTP request methods you can go here you can open mdn and now you can see the explanation for this you can see each one and this is how you learn and this is a great thing about swellkit because we're going to spend more time learning about web standards on NDM than actually reading the circlek documentation alright so let's create an endpoint so to show this how this works basically what I'm going to create if I close this so remember we have our here development server which should be running and now I basically want to create this endpoint I want API newsletter and right now it's not found but let's see how we can create it so I'm going to open the sidebar and in Source routes I'm going to create a special folder API slash newsletter this isn't convention you can name it banana or whatever you want in some Frameworks this is convention that you have to have an API folder but I'll just use it to know where these type of files are if this is some API that's used across the app so here in routes I can say new file so you can start creating some folders I can say API newsletter and then you have to create a special plus server TS file and now we can close the sidebar and now we can create the functions that match the HTTP request methods so we're going to create one that's API newsletter this is going to be the get request and also we're going to create a one it's going to be newsletter post request and how do we create it well we just say export const what we want get right and we're also going to use our request Handler type if you press enter it should Auto Import it or we can do this and now we can say async we didn't really have to and here is an event which comes by default so we're going to talk about this in a second so we're going to do this and let's just return some text right so remember how we say that it returns a response and we actually looked at the response in the Network Tools so you can say return new response and you can just return anything and also see this awesome type completion you can see body and the options you can just say hello and now if I save this it should return hello and if we look at the network tab you go here just refresh here is the newsletter and this looks familiar right so we can see a request method status code content type text so basically we can infer that the browser does this by default if you don't Supply anything so you don't have to specify it yourself and the browser is actually smart enough to understand the content type in most cases I also want to talk about the response obviously I'd be thinking about this using this for the first time okay I can probably learn about in the silky dock wrong you're going to hear me talk about all this time about using web standards and response is a web standard so you can go mdn response you can open mdn you can see here the description and now we can go to the Constructor right so here is what we're using actually right new response you can see okay here is the body options but of course if you're using typescript you already know about this because you get awesome Auto completion but you can actually learn more about it here you can see what you can pass in so you can pass a blob array buffer I never use these things to be honest I use blobs array buffer no idea what it is ETC yeah readable streams this is something cool right but yeah this is really awesome and you can learn so much not just about circuit but the web in general which is transferable knowledge all right but let's look at mdn as these options and let's create the options ourselves so you can just create them here like this that would be fine I just want to create a separate one so it's more readable so I can say const options and this is of type response init which should be available globally this really isn't important I just want this to have Auto completion so if I press Ctrl spacebar I'm going to see ah header status and Status text and how awesome it is so let's create our own status right we can say 418 which is going to return the teapot status which is a hilarious maybe in web development and then let's also specify some headers so we can take the mean to the next level and now we can give this whatever name you want like right this is like the part about learning and playing around like all of this looks serious like like your life depends on your drive but you can just play around and hit funds so I can just name it X and what does X do of course X is gonna give it to you now we can pass the options here let's just save it and now when we refresh the page you should see here oh here is our status code and what is that status code you can see 1400 I'm a typo you can learn more about this on mdn the origin of this joke and we can see something interesting here so here is our own header X and what does X do X is going to give it to you alright so this is awesome but let's say for example you want to subscribe someone to your newsletter or you're using some other API so we can create a post request and let me just close this and now here we can just go to our post so basically we can use a form we can use the method type post and this is going to Ping this instead right because when we visit this page it's going to trigger the get but we want to trigger the post which we can do using a fetch request which I'm going to show you in a second but yeah let's just do that so how do we do that export cons post and you can say request Handler which would be the same type and let's just say event I'm just including this so you know that this is what you get by default even if we use it or not but in this case we're going to use it because we can get something interesting from the event which is the request so let me just show you that so you can just say it's going to be the data from the form right because we're going to submit it so you can just say data our weight the rent advice on the request typescript help us out so you can see here is some interesting thing which you're going to talk about later so you can just say event request you get the access to the request and what is on the request form data beautiful so you can get the data and now we can get the email from the data so let me just move this up so how do we get this and basically this is also something you can look up on mdn the form data and how you work with it and you're going to find out that you get a value from form data by using the get methods you can say get and you're going to have a field which has a name email right and then here is some logic so you can subscribe you can subscribe the user to the newsletter but here we're just going to console log out the email when we submit it all right so now here is the interesting thing so remember how we had new response so basically we want to return Json and I'm just going to create a new line so this is more readable so basically we need to stringify first whatever we get so we have to say Json certified or some experts would say we need to serialize it okay so to do that and now we're also going to return our success true so basically when we get this response we can show a success message to the user right so we're going to return a success shoe because this isn't going to get returned if this fails right this is just going to explode okay so now for the headers this is important we can say headers to do it like this actually you need to rename it and now you set headers like this and again you'll learn about this also in MD and how do you set headers so you can say content type this is the same thing we've seen in the network tab and what do we want application Json and we also need to match it because this is another one we need to click like this and when I save it it's going to format it anyhow so that all goes through the window which is really awesome so yeah we can do it like this and now we just need to use it so how can we do this let me just go to the sidebar and here in our routes I'm just going to open the default page so now let's pretend that we're trying to make a sign up right so we can say H1 newsletter we're going to have a form and we don't have to specify an action this can this is by default get actually not an action this is the URL the method we're going to have to specify which is default get but we're going to specify post but actually we're going to use JavaScript here so we don't really need this but you can also get this from the form even if you use JavaScript but let's keep it simple I'm just going to remove this I'm going to have on submit and I'm just going to use this handy thing from cell prevent default and now we're just going to create a function subscribe so here instead of submit you say subscribe and default is going to be submit so you don't really need this let me just go here and now we just need an input it's going to be of type email you can just say yeah type email we can just give it a name and this is really important this is how we get the value from this thing so we can just say email and you can even remove this of course introduce some semantic markup in your HTML and let's just create a script tag and now here is the more tedious power because we actually have to do this TDS part where you have to fetch the endpoint and Etc and that's why swelkit has another more awesome way of working uniforms which I'm going to save for another part but for now we're going to do this I'm going to say async function subscribe and it's going to return an event which is of type event so now we can get the form itself remember we can say event Target or you can use this but I really prefer this and after paste typescript we just need to say hey this is a HTML form element to treat it as a form element and now we need to get the data and remember this is what we get here right when we pass it back okay so how do we do that we say const data new form data Ah that's interesting right so this is something also you can look up on mdn and we pass it back the form and now this is going to return the form values right which we can use and remember now we need to Ping our endpoint how do we do that well we use fetch oh wait fetch what we want to Ping API newsletter and now we need to give it options right so here is an options object and now we can say method post ah how awesome is that and now for the body we return the data for it so let me just save this and again now we're going to return this data from the form whatever we passed in and you can also have values here that you can bind if you want this is honestly way simpler and closer to the web so this is what you're going to get here from the form data remember we created this form data here how awesome is this and now we have our own endpoint because we have an actual server and we don't really need a entire server we can use serverless functions from a cell which is actually perfectly suited for this because you can spin up one action at a time than having to have some server constantly running in the background so now we can get the email and this is going to log out the email and you're going to see the in response if it's successful you're going to see a success message alright so let me go to localhost by 173 here is our form I'm just going to move it here and now we should see this locked out on the server if I open the terminal here so let's just give it an email here say that I want to subscribe and actually let me just open the network tab here so I'm just going to press subscribe and you see ah here's the email right okay and now you can see here is the fetch request how awesome it is so now we're going to go here you can see it made a post request to API newsletter and now we can see the payload the preview it Returns the success and you can return whatever you want and now since you've done the fetch here you can go even further you can take this from the response and then you can update some State inside your app if this return whatever you want right and then you can show whatever you want to the user and how awesome is this and you can use this in many different ways so for example if I go to even my site you can see for example that all of these posts have view counters and basically that's done by having an API that just pings Super Bass so it just increments the count in some database whenever someone visits a page and this is how you can use an API endpoint whatever you need to hit some endpoint or whatever an API input is really useful and again I want to repeat the install Kit which is going to be on another part we're going to explore a much better way with working with forms in cell kit alright so this was just an introduction to API endpoints but what I really want to make I want to make an API post endpoint so you can go to API post and this should return all the posts from a database so you can use it across our app and this is what I'm going to do next so let me just close this and let me just keep this open let's close the terminal so now I'm going to close this and we can close this so now we're going to create another route so I'm going to go to API and I'm going to say new file and this time I'm going to create a post folder I'm going to say plus server TS and now we're going to use Prisma to fetch the post from our database and return them as Json so we can use them it's going to be exactly the same as the dummy Json API and later we're going to even enhance it so I can show you how you can make your own API more interesting and special alright so let's close this and now if you use the circuit extension you can just use kit and you can just say kit endpoint isn't going to give you a much quicker snippet you have to type all of this out so we can say export cons get and again we can just import this request Handler they should input it here and let me just instead of returning this I'm going to show you something so we can go here and now we just need to use Prisma to get the post and how do we do that well first we're going to import our database remember we created this DB from and this is aliased automatically for you lib database see it already knows and this is by default in circuit and you can also Alias other folders if you want okay so how do we get to post and this is going to be simpler so we just say cons post and now we need to use Prisma so we can say I'll wait DB post find many and that's it this is going to return all the posts and I'll remember how we said that we need to return so we can say return new response and remember how we had to stringify and Etc to return on Json response well this is so common in fact that circuit has a helper function for you so you don't have to do this so you can say return Json if you press enter it should Auto Import this from toolkit so I can place this at the top so now you can say return Json now you don't need to do any of that now you can just return the post I can save it and now this should work so now let's go here you're going to refresh this and now we forget to post awesome and is the almost same exact thing like you get from dummy Json and here is our database so remember we had a created updated title now we get the slug also also we get the published Etc if that's what you want and here are all the posts that we had in our database and now we can go here to post we can see again same like that other API right we have a request method status code here is of type Json we can go to the preview exact same thing here is the raw response right and how awesome is this so while I'm here I want to explain the event object to you because it's very important and you're going to see this across your entire cell key deck when it comes to loading data and Etc so what I'm going to do I'm just going to use an event here and then I'm going to console log it out so I'm just going to say console log event and if you're using types of course you can just structure here you already see all the options here cookies fetching Etc but let's just do this and let's open the terminal let's save everything and now when we reload the page we're going to see how here is some interesting things here so you can see so this is a method to get and set cookies in circuit then you also have fetch which has super powers which you're going to see how it works in a second so this is going to give you extra features like inheriting cookies and authorization headers for the page request it can do relative and internal requests on the server and it's also going to prevent additional requests because it inlines the response from HTML it really doesn't mean anything but we're going to see how that works in a second we also of course have params of the current page so remember previously when we had slug or whatever is going to give you those params we already seen how the requests were so it's going to give you the original request object the root has the information about the route so if you go here is the request there's a lot here's the route API post here's the URL so you can get whatever you want from here same as you can from that store that we used previously if you remember from the last part and then you also have another interesting thing which is a way to set headers so this also returns set headers which is right here so you can set the headers for the endpoint or for the page so let me actually show you an example of it and this is going to be really cool so we can go here and again we're in our post endpoint and now remember how we said that this should find many I'm just going to remove this here I also want to get a random number of postage time so you can see that caching works so you can specify to Prisma take and we just need to generate a random number between 0 and 30. so we can say math round because it's going to return a float or whatever so you can just say math random and now we need to multiply it by the number of posts so this should always be random and we're going to fetch this post and I'm going to show you how this works and now here is how simple it is to set your own headers so from the event we have set headers and now you can specify your headers again cache control and you also learn how to do this on mdn so you can say max age is going to be 60 seconds so this is going to be fresh for 60 seconds and whenever you make a request to this it's going to Cache it to your disk and show it to the user so you can go to mdn HTTP caching it should open the HTTP caching link so you can learn everything you need to know about caching of course alright but before I show you that let's first talk about how we can actually show the data on the page alright so let's see how we can show the data on the page and this might look familiar to you because you're going to use client-side rendering and this is how you've done it in the past in react View and soiled before soil kit first I'm going to remove all of this code because this is just an example so you can just save it and then I'm going to add a script like this and now I'm going to create a function to get the post so now we can say const response I can say await Fetch and remember here is our API post so if I go here and just copy this over if we go to API post it's really just like any other API we can ping this and we can return some data nothing special here so you can just go here we can say const pause and thankfully press machine is the type for us so we can get a post like this we can specify this is an array of posts and I can say I'll wait response Json and let me just clear it like here and I'm just going to return both so now that we have this promise we can use a special a weight block from swelt to get the data and show it to the user so I'm going to go here I'm going to say H1 post so if we save this we can see here the posts and now we can start using the block we can say I'll wait we have to use the promise get pause and now here you can set the loading data this is only going to show for a brief second because it's really fast and now when you have the data you can say then you can name this whatever you want I'm just going to name it post I'm also going to use my snippet that I used previously just so we can see what's on the page and now in case you have an error you can say catch error like this and I also need to close the weight block you can do it like this and now we need to say p you can output the error message in case you have an error okay let's save this and you already seen this took a millisecond and now okay one two three four so you can see we got a random amount of posts even though there's 30 posts and remember this is because previously we use take and now we use math random so now remember because we set the cache control header this is going to be fresh for a minute so no matter how much you refresh you should see 25 posts so here you can see here is 25 posts and the way you can break this spell if you go to the network tab since we disable cache if I refer this right now this should refresh with a completely random set amount of pause let me just go here so here you can see it returned 21 if I refresh it again he's returned 11. and of course you shouldn't rely this in production you should use S max age so you get it cached on the CDN so for example if I go here to post let me just see Max age 60 so you can see here it's cached and it's also going to say that it's red from disk of course let me just enable it like this so we can see the request and you can see here it says disk cache so now when you open it you can see 200 okay from disk cache and when you're using a CDN in your header is going to have a header here that's going to say hit for the cache and you would set max age to zero of course if you're generating a completely static star generated site you really don't have to think about this when you upload it to something to your cell they're going to set the cache to Forever Until the next time you redeploy or whatever so basically you would set something if you're using server-side rendering you would set this to public you would set max age to zero and then you have X xh 60. so for example if you have a deluge of traffic you're not going to hammer the servers it's going to get cash by the first person it might take the initial response more time but the subsequent responses are going to be much quicker so this is how you set the cache control header if using server side rendering and want to Cache something on a CDN but yeah I can just revert it to what I had before just as an example and that's basically it and also let's actually display the post so I'm going to close this and let's go here oops I'm just going to remove this and we can just use good old swell to Loop over the data and you can also see the caching in play if we let's see do I get auto complacer awesome we can just say showing so you can get the pulse length so showing amount of posts and then let's just Loop over the data let me just create space here so it's easier to read we can say each post as post and now we can close the each here and now we can just display so you can say UL I I'm just going to show a link so you can just say slash post this is what you're going to use in the future and now we can say post slog because remember this is why we created this log so we have here to visit the post and we can just say post title and of course if you want to be clever you can destructure it here since we have type completion you can see all of the things that are available to you so you can say post title and Etc like this slug title and now we can even remove this and now when I save this showing 25 posts and this should be cached showing 25 posts but remember we can always break the magic spell if we go here disable caching and now it should always return different data how awesome is this all right Fred so we've seen how we can show data on the page using client-side rendering but this comes with some problems for example here we have posts and really want great SEO and now when Google visits us or the gold bing is going to have problems parsing this JavaScript of course search engines can parse JavaScript in theory but it takes compute and really is Google going to waste resources on you so really don't believe those fairy tales and people tell you that it's fine to just use JavaScript it's not for many reasons because if you want great SEO you have to use server side rendering so let me show you what this means if you go to view page Source here you're going to see loading let me see if I can zoom in yeah so this is the only markup you're going to see and why is that available because we're using client sign rendering and if we go to the network tab I'm just going to refresh this and let me just go to the document here and this is the only thing that returns so this really isn't server side rendered so basically you're just getting an empty shell HTML file and whatever has to load here after the fact it uses JavaScript or swelt in this case which is why when a search engine comes here unless you can execute a JavaScript on your page and this is why you won't get great SEO because this is what the search engine is going to see unless it's able to execute JavaScript on your page downfall of this is that the JavaScript has to load first before it can even start fetching the data so it does a round trip right if you're making a dashboard or whatever like who cares right but for example something like post here or Etc where you want great SEO server side rendering is a must almost using server-side rendering is just a much nicer user experience and is going to avoid loading Spinners everywhere so instead of using client-side rendering I want to take advantage of serious side rendering in circuit and fetch the data before the page loaded which is going to result in a faster and more resilient app alright so how can we do this let me just close the developer tools and also going to close this view source so how we do this in swelkit a Page Plus wealth can have a sibling plus page TS file that exports a load function which returns data for the page and nothing else so let's create that file I'm going to open the sidebar in here in Source route so remember here is the page resulted root of routes you can create new file Plus phds and now we need to export a load function so we can say export const load the type is going to be page load and it should Auto Import it for us which is nice we can just say async it also takes an event right so you're going to see this everywhere when it comes to data loading and now we need to do something special we need to use a fetch method from circuit so it understands the relative paths on the server we talked about this before if you remember so you can say const response await fetch and now we can just point it to our API so you can say API post and now we're going to get the response I'm going to use the post from Prisma which is going to Auto Import for us which is nice now we can say our weight response Json and now we just return the data so you have to say return return an object and now we can return the posts the posts are going to now become available to our page inside a data param so we can see if we go here I'm just going to remove everything here and now we're going to start by creating a script again and I'm just going to say export let data and this is already typed for us which is really awesome because swelkit here generated the types post here and now we can use those so now we can go here and we can say page data and this is the only thing you have to import here so now if we save this and let me just however you can see this is already type which is really awesome all right so now we just need to use this data so we can just say post and again we're going to do the same thing I'm going to say showing post actually pulse length oh it's data post like maybe data pose length posts okay sweet so now we can Loop over it again I can say each data post right as post and now we can close it here and now let's just say UL I again we're going to use the link post so we want the slog if you remember post Slug and we're going to use the post title all right so let's save this and we should see our data which should be server side rendered awesome and again we can just refresh it we're just going to get a random amount of posts so now when we go to the network tab and let me just refresh this you can see we actually get the entire document so here you see 11 posts here you see the same thing so now when Google or the legend Bing comes around he's going to say oh here are some poles okay better in this and boom bam thank you ma'am now your number one ranked on Google or whatever congrats and also another thing I want you to note is that you can find a single fetch request here so if you try you couldn't because why it happens on the server right and you would only see a fetch request if you navigate to some other link because silkit at that point as you learn in another part becomes almost like a single page application because when you first visit the page there shouldn't be any links right so let's see if we go to posts so even if it says not found now if we go and preload home you should see here is the fetch request because this is basically client-side rendering but if you go to home and your first time visiting the page is going to render on the server and that's why there is no fetch request here and also another thing I want to show you how I mentioned and this is one that gets me all the time I use rarely fetch like this here because I'm using a database or whatever but because of that because you don't use it all the time you're going to get into this issue you're going to forget about this feature because fetch works on the server because it's fully filled so you're going to have an event and this all looks great right okay great this is going to work great and now you save this and you get an eternal error which is honestly not that helpful and now you're going to waste half an hour here trying to understand this cannot use relative URL if you like know about what I talked about this should make sense but if you don't then you're like okay what does this even mean like why does this work like just going to get confused so remember this is why this fetch is useful because it comes with superpowers so this is just going to work also remember how I also mentioned that fetch inlines the data and what does that really mean so for example if we go to the page Source here here you can see here is your actual HTML ah but look at this here is the data itself so cell kit isn't going to have to do the same work again because it's just going to inlay this data and if nothing has changed it's just going to show the data so let me just close this another tip I want to show you when you go to page as well so this is great data post but honestly you're going to have a lot of things and it's going to become a pain having to constantly use data dot whatever but we can use reactive declaration so we can destructure posts so for example let's say you do const I'm going to say post from data so this is fine but this really wouldn't be reactive because when you update this nothing is going to happen so the next step you can do is use a reactive declaration which is a dollar sign but there's another problem this isn't valid syntax so you can just group it like this and now if you save it everything should work it this is now reactive when something changes it's going to update data so now we can go here and I'm going to say Ctrl D so everywhere where we use this I'm just going to remove it and let's also be a hot shot we can say Select Title can remove it here save it and you just close this and everything should work great great but sometimes you only want to run code on the server the plus page.ts file is great for fetching data for the page but also you have to keep in mind that it runs on the server and browser and it won't work if you need to use some Secrets or want to use the file system or database I'm going to show you this by creating a slug route that should get to post from the database using the slog parameter so I'm going to open the sidebar and inside our routes either going to create a new folder so I'm going to say post I'm going to create another folder Slug and I'm going to create page.swelt and let's just give it a title this should be post so now when we get the post here and go we should just see post you can see it's going to update so this will show the same but we want to dynamically show posts and this is also why we created the Slugs which is really awesome so now what we have to do is fetch the data on the page like we've done before so here in post we can go to Slug and remember we can create a page.ts file and we're going to see why this won't work in a minute but first I'll just create the code so we can export the load function we can say export const load page load let's import it and now we can say async I'm going to need pyrams from the event because we're going to take the slug and we're going to fetch it from the database so now we can get the pulse we can say cons post await if we start typing DB and press enter it should also Auto Import and this is why typescript is really awesome because it's really smart about these things in your editor so we can say DB post find unique remember because we specify that this lock should be unique so this is really easy find unique and now if we get Auto completion what are the options where right and now we can just give it a slug it also knows this select the unique identifier how do you get the slug from the param slug if you go here for example and you do console params you should see the slug bag which we already learned in the previous part so now let's do some error handling so for example if there is no post we're going to throw an expected error if you also remember that from a previous part we're going to say Throw error so this is going to be expected let's Auto Import error from cell kit so you can say for all error let's give it a 404 and we can say post not found and now we can return the post if everything is all right and basically that should be it so now if you look at the terminal remember how we console log this out here let me just refresh it so you can see this is the slug so this is how we can fetch data as we've seen in a previous part when I tease this and now we're going to see why this doesn't work you already see we have an internal error so if you go here to our console you can see error prismaclient is unable to be run in the browser okay so how do we solve this like is this all code for nothing we're going to throw this away nope it's really simple as renaming plus page DS to plus page dot server.ts so it's only going to be run on the server so if I go here I'm going to close this so inside your sidebar inside the slug folder we're going to rename page DS Dot sir DS and now if we go here we need to change some things instead of page load this becomes page server load so we can remove this type here let me just save this and I'm going to refresh and everything should work when you're accessing secret environment variables talking to a file system or a database you have to use dot server but by default just use plus page Ts for everything else alright so let's dynamically render the post and show it to the user so we can go to page swelt where we have the slog so now we can actually get the data right so let me just remove this let's say the script and now we can say export let data nothing changes here you're receiving the data we can Auto Import page data like this and I'm also going to create a helper function that's going to format the date because we also return it from the database I'm going to say form a date it's going to accept the date it's going to be of type date and we're going to return this useful JavaScript feature we're going to say Intel date time format which is a really nice way how you can form a dates we can say English and for the date style we can use long and then we also have to say format and we need to pass it the date and that's going to be great so now we can show it in our template so I'm going to create a heading group and I just say H1 and I'm not going to use the fancy destruction because I really want to focus on this concept so I can say data post title as you can see we already have great Auto completion from typescript which is awesome and if you're not using typescript of course you can use JS doc so you just copy paste.js.com and here you will get the same awesome type completion so this is going to be the title and I'm going to add a subtitle and here's going to be the date so let's just do date post created at you know if we say we should see this and this really doesn't look pretty right but we can already see our post is working and I'm also going to have some content here and if you had some HTML or whatever in our post which we usually do right even when it's markdown we can just use HTML from 12 we can say data post content additional choice for this page all right so now when you go to home his mother has always taught him you can see this is going to work the other post is going to work in all the other posts are going to work and now you're dynamically rendering data but let's also format the date so here we can use our utility function you can save this in a utility folder or whatever so let's just see how this is useful really simple to form a date this way ah you can see January 10th and you also have other short I think if you use autocompletions again white ice cream is so awesome you don't need to open the docs just see all the available options to you January 10. it's a full this is going to give you the full idea we're using long so we can just keep it at that so another lot has changed beside the file name and the types for the load function becoming page server load instead of page server in general whenever you need to create an API or make a HTTP request use plus server.ts and when you only care about data for the page use plus page DS or Plus page.server.ts in this section we're also going to talk about how your layout files can also load data your plus layout of cell files can also load data using a plus layout.ts or plus layout.server.ts file the same as your plus page.s cell files anyway wondering why would you do that well the superpower of doing that is that the data are returned from layout load function is not only available to that layout but it's also available to all the child routes meaning you can pass data like a hot potato for your routes let me just quickly show you how that looks like so here in Source routes you can see how we have the root layout here so if you want to load the data you can just create a new file let out.ts here and now if you have the circuit extension you can just do this but instead of page load the type is layout flow so this is going to get imported from you you also get the event the same as before and now we're just going to return a message and nothing else I'm going to say return message hello and now this data is going to become available to the layout page but also to your other child routes I'm going to press Ctrl p and I'm going to find the layout in your Source routes and here if you say export let data and we can give it a type layout data you can see this is imported for you and if you hover over it you're going to see that you're going to get the message which is awesome so now when you output it like here you need to snippet you're going to see message hello so let's take the same block of code and now we don't really need this here let's just remove it so now you can go to any child routes and you're going to be able to use that data so we can go to post where you have the slug for example to page swelt and now if you hover over this you should already see ah here it is the message and now if we put it here now when you go to a post you should see not only the post that returns for the page but also the message from the loader function from the layout this is really powerful when you have some data that you want to reuse so I'm going to show you how we can take advantage of that here in the post since we don't have a page yet we're going to create it but basically what I want here I want a sidebar that's going to give us a couple of posts and on the right I want to show the post that we've seen so far but also I want to recommend posts that are going to be the same as in this sidebar and we're going to use a layout to achieve that so you don't have to create a special file just to fetch the data for post or whatever but first i'm going to remove this because we don't need it and I can just save this and we don't even really need this file so I'm going to find it here and I'm just going to delete it so first thing I'm just going to so I'm not blinded I'm going to go here let me just collapse everything just so we know our footing we have Source routes here is our post so remember we're going to visit post nothing here so I'm going to create a page dot swell file just to get started so we can just say post and we're also going to include a paragraph We can say you can browse pose here and now we're also going to create a new layout so again under post layout.swell and let's just name it layout or whatever it's really not important for now because first we're going to fetch the data here and you can also see if you just give it a slot we should see everything else but we're going to get back to this first let's create a Plus layout.servert Ts file under post so you can say Plus layout server TS and why server TS because we're going to talk to Prisma of course so let me just collab this and we need to export a load function export const load the type is layout server load so this is going to get imported we can say async and again you get the event here if you need it just like before and we can just say const so you can use Prisma if you press enter DB it should import it for us so you can just do it like this and we can get post find many because we want everything and now I'm going to specify the fields I want let me just do it like this so I can say select I don't want anything else I just want the title and I want the slot let's say true and I'm going to take four results nothing else and now we just need to return the post so I can say return pulse and basically that's it awesome so since we use this now this data is going to be available through our entire slash post route so we can go to layout 12 and I'm just going to remove everything here I'm just going to add a script export let data so we can get the data the type is going to be layout data which should be imported like this awesome now I'm going to create a layout like this we're going to have some basic styling let me just make space so it's more readable I'm going to create an aside here's going to be a nav inside H4 we're going to have posts and now here is going to be some list and now we're going to Loop over each of those posts so you can see each data we have types here data posts right data post is slug title so sometimes this might be tricky here we have some polls but in that case you can press Ctrl P you can use the pointy boy and then restart the language server or worse you can restart your development server and the type should be generated typescript is sometimes slow and that's how it is because this is really complicated when you think about it what it does under the hood right so if you ever have problems maybe it's not you first maybe it's time clip so I recommend you check that so we can say each here and then say Li I'm going to have a link here post is going to be slug and this is going to be title since we just structured it so awesome here you can see we have the sidebar everything is good we have our type here all right so now let's show everything else remember we need to use slot here this is going to show our post okay so now we just need some basic styling that's how simple this is how awesome is this right so I can say display grid grid template columns so I'm going to say the Cyber should be 200 pixel not responsive 60 characters for the post and I want a gap of 4 REM and then I want to do some spacing to Ram let's save it and awesome this is a great layout so we can see here we have it on the side and now since we created this layout when we load the posting it's going to load in on the side how awesome is this and of course this is not the most responsive thing you can make it more responsive but yeah and I'm also zoomed in so that's why it is but yeah let's just keep it zoomed in for now so let me just give you a summary we created a new layout for the Post route just so we have some posts here in the sidebar on the left and just so we can load posts here this post is coming from this file which is slash post page.12 so we can do whatever here and now when we load a post because we're using this layout where we have this slot here now every post that we pick here is going to get loaded on the right and this is how that works how awesome it is okay let me just zoom in just so we see everything okay hope this is visible but yeah basically that's it but now I also want to have recommended posts here they're going to be the same as they are here and in our sidebar if I go here to routes post we can see here is a child route of post slug page.swealth if we go here and hover over data hunt what is this oh here we have the post right and the post itself and here is everything that we need right so we don't really need to create a special file just for this plus page or cell file where we can already reuse the data we have so let's show the post so you can go here I'm going to create posts give it a H3 post we're going to Loop over it again UL and then I'm going to use the snippet I have so you can say data post s slug title and now inside here we can do the same thing Li we're going to give it a link this is going to be post slug gave its a title also now we just need some Styles if you save it it should already work but now let's give it some spacing here so if I go create a style just say posts margin top to Ram awesome and now we reuse this data so now let's try if everything works so this is going to load the post and we're going to get the same recommended post and now when we use this it's also going to change the post but this isn't going to change of course and how awesome and simple was that alright friends before we get started with this next part first let's fix this issue so it'll get canceled so this was in our layout post right so you can just say min max we can say actually Auto and Max 60 characters and they should fix it all right that fix my OCD and I feel already a lot better so let's close this and let's talk about how your data is available everywhere so so far we've seen how data Flows In One Direction but the dollar sign page store makes your data available everywhere so let's see how that works if I press Ctrl P I'm going to go to the root layout which is going to be Source routes and now here I can import the store from cell kit which we've already seen in previous Parts how useful this is so I can say import page from Dollar Sign app stores and I'm just going to Output everything here use a store by prefixing with the dollar sign this is just syntactic sugar so you don't have to subscribe and unsubscribe to stores yourself so now I can save this and you can see it's going to Output it for every request so here you're going to have these params and we also have some data so we get posts and remember here are the posts from data that you return from our loaders and here is a post so interesting things happen when we go to a post so you get here post and here is a post with the ID you have created it and Etc so why is this useful you might be confused and basically this is really useful instead of repeating something like SEO on every page you can use this page store to use it for your titles and whatever else you need and you can overwrite it for individual Pages if you want so let's see how this can be useful so I'm just going to remove this and I'm just going to create soiled head here and here is where you put whatever you need that goes in the head of the document so we can say title and now remember we get it from the page store and the beautiful thing is that it's also type so you can say data post and let's give it also a question mark because the post might not exist and you're going to see we're going to update the title here when I save so awesome this now updates the title of the post but of course when you go to other parts of your site this is going to be undefined so you can set a default here if you want to you can override this just for those individual pages but now you don't need to do other complicated things to make this work so if you see when I go to any other post it updates the title and this is really an awesome use case for this another real world example I want to show you is when you're using an off library or doing all of yourself you need to somehow authenticate that user so let me just scroll down here so remember how we said that you can return data firmer load function from your your layout that is and is going to be available for your entire app and here is the perfect use case for that so of course this is more involved you're going to first authenticate the user using Hooks and cell kit and then through this event you're going to get the session or the user data whatever it is from event locals so you're going to get a session here and now you can use this from your dollar sign page store anywhere in your app so in this case for off JS it's returning this session and now you can check it in your template so here you have some file whatever and now you have access to the page store and now you can make a check here if page.data sessions remember this is the same session that you return from here okay then you know the user is authenticated and now you can display any data you want from this you can show the user image or whatever else you need and this is really what this is useful for so I'm just chilling here in our API endpoint and I'm thinking to myself how can I make this API more flat flexible when we first created this API I honestly wouldn't have blamed you if you thought that we just did the same thing that the dummy Json API did but not only do we own this API now we can make it more flexible so let's talk about how we can use the data from the URL first I'm going to remove this limit here and the cache control header since you don't need this anymore and basically if you think about it the URL was the first state manager before any of these fancy JavaScript Frameworks existed a stateful URL means you can use Query parameters from the URL for providing options like filtering and sorting data and circuit makes it easy to work with the URL and that's why the load function has some useful things so we can get the URL from here which is an instance of URL which you can learn more about on mdn and it has properties like origin hostname and path name and also the search params which are going to be really useful in a second you also get the route which has the name of the current directory relative to Source slash routes and you also have params which is derived from url.pathname and Route dot ID and if you go here you can console log it out so you can say URL route params let's open the terminal I'm going to save this let's rerun this so now we can see all these options on the URL here is the route which you can get the ID and your params have other info if you have those but what I want to do is to improve the existing post API so I'm able to specify the amount of posts I want and set the order so I want something like this I want to go to post I want to be able to set a limit and I also want to be able to set an order that's descending or ascending and basically now when we look here we get the search params and we don't really have to do any crazy regex or whatever to get this it's already parse for us we get the limit we get the order and this is all thanks to the web platform again I know you're already tired of eventually in the web platform all right so if you go to mdn you can learn more about this here is the same thing URL search params and you're like okay how do I get anything from this okay has get all okay Etc or you can be a true chat and just use typescript in your project so you can just go here and now since we have access to this we can create a more flexible API so let me just close the terminal I'm going to remove this so we will need params route we're just going to need the URL and now we just need a way to get our limit in order so I'm going to say limit and this is going to be URL which is URL search params and now we say get what we want to get the limit it's already parts for us right which is really awesome and now we can set a default if there's no limit just return all the posts and now we can set the order we're going to say we're going to search params again get order or we can set the default here we can set ascending and this is going to return a string but we want a number so we can cast it here to a number we can go to the end and you can just save it like this so in our query here let's just make some space we're going to add some more options Prisma has this order by options and you can select what you want to order it by the ID and of course it already has options since we have great Auto completion it's ascending and descending and of course this is why intentionally designed the API that way because Prisma expects ascending or descending and now instead of using a literal string we can just say order and it's going to complain about some things really it's not important we also need to specify the limit so we can just say take which is going to be the limit not order so yeah that should work so now if I go here I'm going to save this and right now nothing is happening we also need to refresh so we should get back four posts and it should be in the reverse orders which will start from 30. so let's do this and awesome now we get back 30 29 28 27 and the beautiful thing is that the order here doesn't really matter so we can for example remove this we can just say limit or if we don't provide anything it should work the same and now let's just say order so you can say descending so this will give us all the poles but in reverse order and everything works great so honestly that's it for this session but I actually want to include some bonus which is more food for thought so using the URL for State Management is not a unique concept and something we just started rediscovering because Frameworks like swelgate make working with the URL great again so you use for example to having component States for something like search but you can share the link with someone else so here is an example of this if I told you to make a search like this you would probably do something similar like this but you would use some state in your component like the search query and that's how you would do it but in swellkit and these other Frameworks what you can do is update the search params in the search params when they get updated they can rerun your load function and this can update the data on your page so as you can see here is an example where you don't need any client state or state in your component this is basically just has a form and it's going to trigger the search and then the search get updated the data is going to get updated for the page of course you don't have to understand this everything this is as I said just bonus content and something I honestly think even the Smoky dog should include because this is really almost an old way but new way of thinking for people so for example if I go here and let's look for Angelo and we get Angelo back and we really had no State and we just also show you how this works in practice I'm going to zoom out because this UI is honestly mind-boiled sometimes so here's what I want I want to open this in the new tab so let's just go to the end I guess a good copy to your last meter so you can see what's going to happen here okay just click down the exit on someone but let's say let's search for Angelo again and now as we typed if you go back to Ariel you can see this was updated real time so for example imagine if you're working on a dashboard or something how useful this would be and now if this was a real site which it is of course I can just share this URL with anyone like I can just copy this I close the tab right proof look at that confidence now I can just go here leave I guess it's going to close it but yeah you can see how this works and now you can preserve your state in the URL and I also want to give a shout out to this Library which you should search params this what I showed you right now looks a bit boilerplated light but here is a Great Library that someone made which makes this really easy so look how simple this is compared to what a show this is even simpler and here you can just import the query param from circuit search params and you can just update the query param like this and there is another great example you can just bind the value and update it easily like this so I think this is something really exciting and something that we just started rediscovering again if you're in the JavaScript landscape because probably everyone else that works in PHP and those other environments are probably laughing at me right now this one is going to be a bit brain twisty we're going to talk about using parent layout data so far you'll learn how data returned from a parent load function becomes available to plus page sweld and plus the layout cell components over the data prop that's great but what if you need the parent layout data inside a child load function in that case you can await the data using parent I want to emphasize this it only works if you return the data from a layout to show this I'm going to go to the deepest route which is our post so I can open the sidebar I can go to Source routes posts Slug and I'm going to open the plus page of server TS file and now here we have access to something interesting we have the parent method so let me just make space I'm going to say cons parent data I have to await it I can say parent and now let's log it out pair in data when I run this code what do you expect to see in the output let me just open the terminal and now I'm going to navigate to a post it already pre-loaded the data so we can see something interesting in return the post and if you guessed that those are the four posts from routes post layout.30ts you would be right because that's the only parent layout load function that returns data so far so we can go to post layout like this and here it is here is a return the data from the load function in the layout so I'm just going to close the terminal another thing you have to keep in mind is that you have to be careful to not introduce a waterfall if your data doesn't depend on the result of the parent because load functions run in parallel if you never heard about this when people say waterfall they usually mean a traffic jam in your network tab so for example if you request something from another old function now that load function has to stop rendering because it has to wait for that parent data to get the data for the current load function and anyways basically get into what looks like a waterfall in the network tab so I'm just going to close this file and open a new one just so I can show you an example so you can pretend that for example this is um page server TS file and now we export a load function like before so we can say cons load which will be page load for example and now you can say async and now we can destructure the parent so let's look like that and now let me show you what I mean so first you would want to get the data from the parent first in this case you obviously can't avoid it this is why you're using it because you depend on the data and you can say parent data you say await parent and now we have the Second Step because you need the parent data and say data and now you have some function a call to a database or whatever get data now we can paste it the parent data hey this is fine if you have to do it but what the silky documentation says is that you shouldn't do this and you should await the parent less so you don't block the rendering so basically what happens here parent load function runs first we can even give it a hour less and then you have here this load function is now blocked because it has to wait for the results of the first one so you can just say stop so now we have a better idea how this can stop rendering so here is the ideal that you should do if you don't depend on that data so if you go here so again the first step this load function fires off so you can even give it a nice running Emoji like this we also copy this over so you can just say const data await get data not this get data and then you can say second the parent load function fires off const parent data await parent and now you won't run into any blocking issues this is going to fire off then this is going to fire off and now the load functions can run in parallel as long as you keep this in mind you should be fine I hope you're not tired because there's one more thing we have to talk about and that is the secret life of load functions you should understand how load functions work because you're going to need to rerun a load function for the page which circuit already does for you behind the scenes in most cases but in some cases you might want to do it yourself and how this works is that spell kit tracks the dependencies of each load function to avoid having to do the same work during navigation so for example let's take a look at the load function for the slug which shows our post so if we type in Slug we need to go here the dependency here would be the params so each time params dot slug changes circuit is going to rerun the load function let's look at another example so we can open page the TS in our routes and what is the dependency here the dependency here is the URL inside the fetch so API post as well can see that the post data hasn't changed it's not going to rerun this function when you navigate to other pages and remember from the start how this goes full circle this is why this special fetch is going to inline the response in the HTML so it's just going to reuse it also a load function that awaits the parent data from another load function will rerun if the parent load function reruns if you need to manually rerun the load function selfie provides you some useful functions like invalidate which you can pass a URL or you can use invalidate all which is going to rerun every load function so be careful with that one so let's look at an example here I'm going to close this and you can also create your own identifier so for example we already mentioned how this is an identifier but you can create your own using the pens so we can use the pens here and you can name this whatever you want you can go here and you can say pens and you can name this banana if you want or whatever what I'm going to call it pulse or the dog show you this really neat naming convention you can use app or whatever I'm just going to keep it simple and name it post I'm going to save so I'm going to change the API slightly here because I want to show you how this affects refetching the data on the page so what I'm going to do here is return a random number of posts I'm just going to get a random number here we have to say math round and then you have to say math random times 30 because that's the amount of posts and now here in the post I'm going to use backdicks like this and I'm going to say limit because remember we enhanced our API how cool is this and now we can say random so this should return random number of posts when we revalidate this load function and we can save it nothing changed of course beside the API now we get the random number or post when you refresh the page but we don't want to refresh the page we just want to do it manually ourselves invalidate the load function and rerun the data for the page all right so now we have to go to the page which is going to be here's a source routes page remember here we have our post I'm going to move it here so what I'm not going to do below post I'm going to create a button and we can say rerun and this is just going to have a function on click you're going to name it rerun load function we're going to create this function right now function rerun load function it's not going to have any parameters so now I'm going to show you all the ways that you can revalidate so the first a method I'm going to call it is going to use the invalidate from circuit so we need to import invalidate from app.navigation and now the first is using as we defined it here that depends this is going to be that let's also Define a b option which is going to be invalidate again and now we can say API post and question this isn't going to work in this case because we created a unique URL so we really can't account for that but in case we have a stable URL it's going to work all right so let's introduce option number c which is going to also use invalidate but we're going to pass it a callback that takes a URL and we can say URL ref if it includes anything relating to post is going to rerun it and let's also include the last option which is going to be invalidate all and if you treat this as a nuclear option so avoid this at all cost if you can but let me just comment all of this out let me just save it so when I press this button now this should invalidate the data on the page and refresh it so let's see if this works awesome and even if you open your network tab let's go to the network tab you're going to see it's going to make a face request you can see it does a random one each time so now let's look at all the others of course this one won't work in this case because we have a unique URL so if I clear this out try it it won't work but it would work if you had a stable URL so let's see the C1 so I'm going to clear it and I'm going to refresh post now I'm going to use the nuclear option invalidate all so you can also rerun it let's repeat what makes a load function rerun if any reference to a property of params or URL changes if the load function calls a weight parent and the parent re-ran if you declared a dependency with fetch or depends and mark the URL invalid with invalidate URL or if you use the nuclear option invalidate all to force every load function to rerun another thing worth noting is that this doesn't cause the component to be recreated but it just updates the data probe for the page inside your Plus page.selt or plus layout or cell component but if you want to reset the component you can use after navigate or wrap your component in a key block so that's everything you should know about API endpoints and loading data in swelkit in the next one we're going to learn about working with forms if you like what you've seen don't forget to like And subscribe and if you want to support me you can find the patreon in the description thank you for watching and catch you in the next one peace foreign [Music]
Info
Channel: Joy of Code
Views: 18,410
Rating: undefined out of 5
Keywords: svelte, sveltekit, api endpoint, data loading
Id: rsmLu5nmh4g
Channel Id: undefined
Length: 88min 15sec (5295 seconds)
Published: Wed Jan 11 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.