We have some dummy data that we will use to get a grasp on data loading patterns in SvelteKit. Each route gets its on +page.svelte
but we can also provide a route with a +page.js
file that allows us to load data and expose it to our page.
You'll learn how this +page.js
exports a load function that exposes a data object to the page you are loading data to. During this process, we'll use JSDoc to type our page data for some nice types.
Instructor: [0:00] Data loading in SvelteKit is really simple. To get started, all we need to do is come into our posts folder and create a new file called page.js.
[0:11] Now, there are a few different conventions for loading data or for data fetching. You can use this page.js, or you can use page.server.js if it needs to run on the server. Meaning, it needs access to things like environment variables and that type of thing. For now, we can just use this page.js. I've created this fake db.js, which, if you need it to pause and copy this, you can do that real quick.
[0:41] Then in this page.js, I'm going to paste our code. All we're doing here is we're calling that fake data or getting that fake data. Then, we're using this load function, and we are returning a posts object that set to that fake data. This type comes from SvelteKit which is a page load type, which is important for when we come back into our page.svelte.
[1:11] Up here, we can do add a script tag. Here we can say export let data and this is the convention in SvelteKit. We have this page.js that has the load function. Each load function exports a data object. That data object is made available to our page.svelte.
[1:42] That's where this data object is coming from. Right now you can see that it doesn't have any knowledge of what data we're trying to pass it. To do that, we can come back into our page.js file and grab this type. This is js.syntax and then come back to our page.svelte.
[2:01] Let's paste it here. Then instead of page load, we can just have page data. Save this first. Now, if we hover over this, we'll see that it recognizes that this data object has a post object on it with all these fields and it is a post array or array of posts.
[2:21] Down here we can use these Svelte each block and say each data.posts as post. We'll close that. We'll just go ahead and save this. Before we add that, we'll come to our posts. We'll see there's nothing here.
[2:40] Now, if we come back over here and let's add an H with the post.title and let's save that and there's all the post titles. Now, let's just make these a little bit clearer that they are titles and say text to Excel and hover of text blue 500. If we save that, we can come over and we see that works and then let's also just provide a b tag with the post.date.
[3:22] There we go. With that, we've learned simple data loading in SvelteKit.