Check out a free preview of the full Fullstack Svelte with SvelteKit course

The "Layout Data" Lesson is part of the full, Fullstack Svelte with SvelteKit course featured in this preview video. Here's what you'd learn in this lesson:

Rich demonstrates creating data layouts, similar to the UI layouts, that load data for every child route. SvelteKit is aware of layout changes and will not unnecessarily reload the data if the layout does not change.


Transcript from the "Layout Data" Lesson

>> Okay, so just as layout.svelte files create UI for every child route, layout.server.js files load data for every child route. So I suppose we'd like to add a more posts sidebar to our blog post page. We could return summaries from the load function here that powers the blog page in the same way that we're returning it from the page.server.js that powers the index page, but that will be repetitive.

Instead, what we're gonna do is rename this file to layout.server.js. And you'll notice that this page continues to work. It's still able to access the summaries data that's being returned from the layout load function. And so now if you go to the individual post page, we have a layout already scaffolded out here, and we can add a sidebar inside here, just below the main element.

Give it a title of More posts, then we'll create an unordered list, and then we're gonna iterate over data.summaries as slug, title I'm just gonna copy the code on the left into this component And you can see that we're now able to render the summaries in the sidebar on the blog page, as well as the blog index page.

And what's neat about this is that as we navigate between these posts we're not having to go back to the server and reload those summaries. Because SvelteKit is aware that even though the post page has changed the layout has not changed and so we don't need to go and refetch that data.

If you do need to control when that data is invalidated, there are techniques to do that and we'll learn about those later on.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now