Understand How Data Flows Through SvelteKit

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey friends in this one you're going to learn how data Flows In swelkit which is confusing to a lot of people because swellkit is this magical framework that blurs the line between backhand and front end so we're going to talk about what each file related to routing does you're going to understand the order in which things aren't then we're going to talk about some routing how data is passed through routes accessing parent layout data we're going to talk about stores adding custom data to request a bit about satellite endpoints and form actions and at the end we're going to repeat what we learned so far by looking at an awesome circuit data flow cheat sheet I made which should really help your mental model in understanding how data Flows In circuit to help you work on your next idea in this part we're going to talk about the files related to routing in cell kit which you might be thinking that there's a lot in uip overwhelmed when you're starting out you're like oh what is this plus page.ts plus server right it might look confusing but once you understand it you're going to appreciate it how genius it is because when you go to another cell key project if you open a folder for example with some route like post you're going to know 100 that the data for data out is only contained in that folder so let's start so we have a HTML file and I've included this because you can include some scripts here before your component mounts so you can get for example the user preference from local storage and then here you have what I refer to page endpoints and yes this is an endpoint because we're going to see how this works in the network tab because just how you have a standalone endpoint this is the data that gets fetched for your page so slowly creates this endpoint for the page so let's say that you have plus page.12 and you're always going to have a sibling page.ts or page.servertis file which you're going to use to run a load function on the server and you can also use page.ts to run a load function on the client and another special thing about plus page Authority is that it also has form action so you export form actions from that and we're going to look at it later so if we go further down we can see that now we have a layout which is similar to your page as well so you can have a layout.swell that you can get the data from the layout from server.ts or dot TS so you have your server and what also silky refers to this is universal and server load functions so our Universal load functions are ones that run on the server and client and your server load functions are just the ones that always run on the server right other awesome thing about data return from layouts is that the data becomes available to your child routes through export led data right in your child component Pages or whatever and then we have a standalone input which is plus server TS but yeah this is Standalone input so you can use this to make a rest API and a standalone Network can return anything else right basically the page endpoint just Returns the Json for the page in most cases but you can use a standalone endpoint to return text Json XML off stream whatever else you want right and then we have hooks which are really powerful so hooks.server TS runs on every request and returns a response so this is responsible for everything that happens in cell kit because felkit listens for everything inside this client hook so you can even hook into the request or respond bonds and you can change it and then you have a hoax file which is hooks.client TS that runs only on the client and this one isn't that exciting because it only has one hook which is to catch errors on the front end so you can send it to an error handling service or whatever and then a honorable mention we have the plus error.swell page which is just a custom error page you can include in your circuit project alright friends before I continue on to show you the setup I have because I know we're going to be curious so here I'm using a fancy console log I made which is going to log for every route so you can know in what order things happen and here I made a pre-component which we can look at here so this is just my famous snippet I just made it into a component so I can pass the name and value so The Styling is consistent across components and here is the log utility so it's using shock as you can see it's nothing special and then inside hooks since this is where everything starts you can log who is making the new request because we get everything here in the handle function so you can do event URL path name so we know the request started and then we again use this log to log that it's hooks it didn't really gets resolved we know that the page or resource in question is ready so it's sending the response so that's basically it for the setup and let's get started alright so let's look at the order in which things run and here I have the entire zoo in this cell kit project which you can find in the post I've included a stag with example which you can just open and play around with what I have where you can find the link to the GitHub repository so as always we have to start the server so you can pretend that this is in production or something so you always have this running server okay so what is the first thing that happens you go to your url right you type in the URL and now when you press enter you're going to make a get request so I'm curious what do you think in which order the files are going to run my bet is that hooks is going to run first because it should but some things might surprise you alright so enough with the suspense let's just press enter this is going to fire our request which is well going to intersect because circuit is a server right and then let's see what happens so I'm going to press enter now we log this R cool so now it says new request is being made from slash which is home or root so you can see the first thing that runs is hook server TS all your server load functions run so layout server TS page server TS as expected and then the universal load functions run so layout TS page TS this is really curious and this is why you can also pass data from your server load functions your Universal load functions and this might be more curious why is our layout built and visual soil running on the server this might sound weird right but this is because of server side rendering so basically what server size rendering is swell kit needs to turn these components or what they return it needs to get the data and then it needs to return the component as a string and then the server is done so you go to the client so Apple HTML runs then again the universal load functions run because load runs on the server and the client and then the layout is mounted and that makes sense because layout is the parent for everything else so it wraps everything and it makes sense that it should run first and then after the layout is mounted of course the child plus page.soil component is mounted and now when these components are mounted on the client we need to restore the JavaScript on the page again right and this is what hydration is so your component gets rendered Twice first on the server it gets server size rendered and then it has to get rendered again on the client to restore the functionality and another cool thing if I close the terminal and open a new file so approximately how layouts work so basically this is a layout and it wraps everything right so you can have your component here or we can name it page so you have some data from the layout like this data which can get passed to the page again and this is only going to render if there is no error but when an error happens instead of rendering your component is going to render the nearest plus error.sell file so it's going to render this instead if there is an error on your page and then when you have other nested layouts it's like nested layout so you have more layouts and then again you can have your page components inside here or whatever else you want so this is approximately how it works if you're curious first thing you need to do is understand how the swellkit router works so when you enter your URL and visit the page for the first time or you refresh the page manually silky is going to server-side render it and then once the circuit app loads it's going to load the client-side router so you're going to get that awesome single page application experience so let me show you what I'm talking about so let's pretend that you're visiting this page for the first time as you've seen what happens it's going to go through all of this process right and let me just clear this console and I'm going to clear it here so it's clear what happens so when we go to the nested route it's not going to refresh everything because at this point the client-side router kicked in somewhere in this code it is it's really important so I can clear everything and you can also see why this is a page endpoint because we're going to see how it gets data for the page all right so pay attention when I'm going to click on this link is going to perform a client-side image irrigation so as you can see here a new request is being made from nested route it runs hooks the layout server function reruns and as you can see the only thing that changed remember we already have the layout mounted and it only needs to mount and unmount the old component and it mounts some nested route slash page.swelt oh but look at this how curious is this here is the endpoint actually data Json circuit so you can see here at the headers and we look at the payload and the preview here is all of the data for your page so basically every route has this if I go here I can just do this and I can say double underscore data Json and you're going to see this for every route how awesome is this and this is why this is a page endpoint this was also named a shadow endpoint in the past what's also really awesome is that swellkit tucks this data in the page source so it can reuse it so it doesn't run it's smart enough to only rerun the load function when it needs to see if you go to home and if you go to view page source and if you scroll to the bottom you can see here is the special secret sauce from cell kit you can see here it is in the data so this is what swellkit knows is there and you can reuse it for page navigation so it's really smart to only run load functions when it has to and also of course you're using client-side navigation but if a crawler like Google or the gold bing visits you on each request they're made they're going to get the server-side render page so you're going to get great SEO and this means that your site is also initially going to work without JavaScript but I want to emphasize that the point is not that your site should work with all JavaScript but before JavaScript because it's going to be more resilient and then when the JavaScript loads you can use it for what it was intended to enhance the user experience alright friends so let's see how beautifully data weaves through your entire swelkid application so you already know the order these things running so is the layout server TS then it's layout TS page server TS then replacing some data to page DS of course in 99 of cases when you have a route you're going to have one plus page swell file and you're going to have one plus page.ts or dot server file right and you're not going to have all of these files together but they do work together you can have all these files in one place and they do interact with each other so it's important to understand how that works so as we already said whatever you return from layout is going to be available to plus layout.1 cell but also to all the other child routes so let's return some data I can say return and then I'm going to return a number are going to say a and now as you can see here we made the request and now I'm inside the source now so you can see here the home page receives this data so you get a and then the page the data Store updates which also gets this data or you shouldn't be wondering if you go to layout TS what now so what would happen if we return something from here let me save it and now nothing is happening so what is going on right and we can return the same Pro so you can say A2 and we can override it and the last slow function that runs is always going to win all right but what if you had a layout plus 30s file and you want to pass the data to the universal load function the load function has a useful argument you can use which is data so you can use data and now let me just log it so you can show that I'm not lying to you so you can see here it logs in and the Beautiful Thing how we lock things is that you can see where it actually happens so when this gets ran you can see here is our log which is really beautiful and you can also see it here all right so we get this data and returning to so you can do whatever you want to this data right now but I'm just going to spread it like this so I'm going to go here I can say data and I can name this prop B and I'm going to save it and it's going to return A1 and B2 so now we're passing data like a river through cell kit how beautiful is that so let's look at what happens next so we go to page or server TS and this is already going to get the data so this isn't going to get the same result as before but you can override the data you had so far so you can say a 2 or whatever and it's going to override it so the data is always going to get passed from the layout and you might be thinking we could use data here but data doesn't exist for Server load functions right and it's always passed so you can just include whatever else we have here so I can say c free then I'm going to update everything so you can see the data is passed from the layout so you have a b and c and then again if we go to the universal load function here we can overwrite everything so far so for example we can say a 10 B 20 C30 now we can save it and everything is overwritten or I can get the data in a universal function I can spread everything I got so far even from the server TS file right so if I save this you can see you get ABC otherwise we wouldn't get the data from the page server TS so now if I even spread that and then I can include the last one it's going to be D4 so now this is updated for the data prop inside our home route and the page store also got updated so you're already familiar how page.feld and layer those cell files have access to all the data from parent load function but you might want to get data inside the load function from a parent layout load function and this is confusing when you read the docs because they don't make it up front clear that is only gets the data from layout load functions and of course it's going to be a trivial example but imagine if you're deeper and you need to get data from a parent layout load function so we're going to get this using this export here we're going to say data A Plus data b equals to data A Plus data B so let's see how this looks like inside patient server TS file it's going to get the data from plus layout server TS and you can say data await parent and inside the universal function this is going to get the data from the universal layout so you can also say data await parent so what do you expect here to be logged so we already know that we return from the layout server ts1 so this should be 1 or a which is one and then this should be B which is two so let me save this and it should rerun this page so you can see here from the layout this it returns A1 and then again since we passed it down to the universal load function in logs a and two so now we can do whatever you want with this data but in this case we're just going to add these two numbers together which is a trivial example of course but it's a really powerful concept so I can exposes a lot of useful modules which are just stores if you look at the documentation for modules you can see a lot of them them inside here but the one we've been using this entire time was the page store from App slash stores and this can be used for anything to customize your error page to send data from a child to a layout for SEO so you can get the title description and Etc so to show you this example I have an error out here so this is a page that says error and here in the Universal load function there is no load function I'm just going to throw an error and at the root I have this plus arrow.sveld file so this is going to get picked up as you can see here is the error and then I'm going to log the entire page store and if you didn't know if you're inside a cell component and want to subscribe to the store you can use felt syntactic sugars you can use the dollar sign which is going to subscribe to the store when the component mounts and is going to unsubscribe from the store when it gets destroyed alright so let's do one of my favorite things cause things to fail okay so we can go to errors and remember as I said if you have an error on the page instead of your component for the page rendering is going to render the nearest plus error.swelt component another cool thing is that it trigger the hooks client TS as I told you before it's not that exciting just for error logging as you can see it mounted slash error slash plus page yourself as you can see here is the entire page store so you have params route which has the ID status URL form data and the data itself which gets updated when you run a load function for a page so I see people often ask this question they want to return some data from the server and of course you can't use stores on the server I mean you can but then it's just going to exist on the server because the server is separate from your front end a store on the front end is just an object in memory so when you end your session that store is gone and the server really doesn't know about the store and it's also really bad to use a store if you have users so you're going to store global data for that user but well it has an awesome section in a documentation about State Management and to tell you to use the page store instead to pass data to your routes instead of using a store but if you want to use a store you can use a store with context so let me just go to this example stores as you can see here I'm just fetching some data from the endpoint so I'm just going to get a different name each time as you can see here it is if I go here to the layout I just have some users and then I can return a random user so here inside the layout we can use a store so you can say hey const user writable and now we need to make it reactive so we can use this reactive declaration this isn't a story if you're confused this is a reactive declaration in soil because it's always a dollar sign followed by a colon and then whatever is inside here is going to become a dependency so you can even make it shorter like this on one line so user set so we're doing a manual updating of the store using the set method so whenever data user updates which is when the load function is going to run is going to update the store and now you can use swell's context API which circuit itself uses for all of these stores so it's Unique on every page resist so you can set the context user and now when you have this anywhere inside your route you can get the context in the user so now you set the context for this entire route store so whatever children you have and Etc you can get the user by saying get context user and then you can subscribe to the store because you set the store in the context right and then you can say dot name and then it's going to Output the name so let's look at this quickly in the swell docs we can go here and let's just search for it so we can say State Management so let's open that so this is what silky tells you avoid shared State on the server so don't Define a variable like this because a server process is long running in a browser when you close your tab that's gone Boom the memory is why but the server if it's running constantly it's going to store your user here and then everyone is going to have access to this and then it says no side effects in load so again it tells you you shouldn't return data inside an endpoint and set it inside a swell store because this really isn't great and it even says for example you might be tempted to write on stories are the load functions you can use to store value and components as with the previous element it puts one user information in a place that is shared by all users so silky tells you hey just return the data or use the page store of course if you're not using server side rendering it also mentions here that this isn't then as important but in general it's a good practice and then here is the same example I showed using stores with context and yeah that's basically it let's talk about something really powerful which is adding custom data to a request so you might have seen this if you used any authentication library but basically inside your hook server TS since this runs on every request you can use the handle function to validate a user but you can also do many different things you can for example listen for a post request so maybe that's a form and now you can parse the form data and return it to that endpoint you can do all sorts of crazy things but let me show you a basic example so inside of hooks I'm setting the event locals to a secret which is going to be banana and if you're using typescript you're going to go to app.dts and you're going to update the type for local so I set it to secret which is a string and now I have this route here which is going to be locals and inside it's server load function we're going to get locals as an argument here so now we can check if locals the secret isn't equal to a banana we're going to redirect the user to home otherwise we're going to return the information and also be extremely careful with not returning sensitive information from the hooks like the user's password even if you're doing authentication you only send back the you user information but let's first see if this doesn't work so we can save this and now we can go to locals as you can see there's a request from locals it runs hook server TS and now it runs this so it was already redirected to home but now let's input the banana so now when we go to locals it should show the page and also now again we get the request hook server DS and then we see everything we have so again here we have the data since you pass it is from the layout we have access in the child route to this layout data so you can see here is our secret banana alright so far I haven't said anything about Standalone endpoints and that's because there's really nothing special about this you can create a standalone endpoint which can return data or whatever else you want you can get the data inside your Universal or server load function and another important thing to notice is that even if you're using server side rendering you can also use fetch in your components or using client-side rendering if that's something you have to do but for completion's sake I made this API endpoint called secret so I'm ready to expose our secret to the world remember how I told you you can get locals everywhere so again here is the Handler get function inside a standalone endpoint so you can get the locals and now you can just return a response to say it locals secret so I'm going to go here and I'm going to say API secret and let's see what happens so a new request has been made from slash API secret as you can see the hooks run and then the plus server TS file runs and again nothing special here if you look at the network tab you can see here you get a beautiful banana and this is just by default returning text since you didn't specify that it's Json or anything else Standalone endpoints are a perfect segue into form actions so if you want to work with forms you need an endpoint you at least need a get and post HTTP request method right so you can use a standalone endpoint for all of the HTTP request measures I get post patch put and delete but instead if you want to send data from the browser to the server form actions are way easier and let me show you if you haven't used form action so this is just regular HTML right here we're using a form we're saying an action hey this should go to log which is just a query param this isn't anything magical right and then we can overwrite it we can say form action if we want the user to register instead and that's basically it there's no fetch here in JavaScript Etc and this works without JavaScript which is also great but you can also use the enhance sweld action imported from circuit so now it's going to use JavaScript to progressively enhance the form and then inside your server load function you can see here you can have a load function same as before but you can now also export an actions object so you can map those query params when circuit sees this is going to say okay this is a method I'm going to run so you can say login or register and then you're going to see how it works and I'm also logging things here the same as before so let's see what happens when you submit the form so I can say test one two three four and now I'm going to Press login alright so let's see new request is being made from slash actions now the hooks are going to run now the login action is going to turn as I told you this is just a URL how beautiful is this slash actions query param and because it uses this slash swell kit knows that this should be a method and now because you're using Progressive enhancement in JavaScript swelkit is going to invalidate the data on the page because you submit the form and now again it's going to make a request to slash actions is going to run hooks again it's going to run slash form slash page server TS the low function is going to rerun it right and then it's also going to rerun the load function inside the layout and it's ready as you can see it works beautifully and also don't sweat the details because this is a lot to take in at once the important thing to take away from this is that you have a general idea how data Flows In circuit to help you build your next idea alright friends that's it I hope that wasn't too overwhelming and you can always play around with the example but also made this useful cheat sheet how data Flows In silky so let's repeat what we learned first we go to the browser and you start typing the address of your site which is going to be the request and now when you press enter this is going to fire off a get HTTP request which the circuit server is going to listen to and the first page visit is going to use server-side rendering so on the server first hooks are going to run the request then all your server load functions are going to run then your Universal load functions are going to run the components are also going to run on the server because we need to return a string from the server and you can also get the data from Universal and server load function using server-side rendering but you can also still fetch on the client inside your component using client-side rendering if that's something you have to do and then when we're done on the server on the client you get app HTML then you get your Universal load functions because you can run load functions in the browser again and then your page components are going to mount which is layout and page and at this point in your app the swellkit client-side router is going to load so on the next navigation when you go back here and it makes a request is going to do all of this again it's not going to use server-side rendering again but client-side navigation and we also learned that inside the hook server TS file you have this powerful event locals object which is available in server load functions and server TS handlers are Standalone endpoints and we also learned that a parent page can access data from a child route using the page store and we also learned the universal and server load functions can access parent layout data with a weight parent and the most important thing if you have more than one load function for the page the last load function is always going to win alright friends so I hope that clear things up if you like what you see don't forget to like And subscribe you can support me on patreon and don't forget to join the Discord thank you for watching and catch you in the next one peace foreign [Music]
Info
Channel: Joy of Code
Views: 15,017
Rating: undefined out of 5
Keywords: svelte, sveltekit, data flow
Id: ampDDmT3TU0
Channel Id: undefined
Length: 25min 59sec (1559 seconds)
Published: Fri May 12 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.