Is it possible to do the following:
Given a route such as /foo/[slug]
with +page.js
in it to load some data based on the slug, can the data be kept when navigating to /foo/[slug]/bar
and available in the +page.svelte
? The context of this is that there is some file being loaded to render on /foo/[slug]
and that same file is used on /foo/[slug]/bar
, so having the file preloaded is ideal. This approach would also require the file being loaded if /foo/[slug]/bar
is visited first. I believe that load functions perform dependency checking. Reading through the docs, especially under the section about running the parent load function, it seems like this should be possible, but I can't quite figure it out.
Some approaches that would work are to use stores, or to use the layouts option, but is there a simpler approach?
I've tried getting the page data on the nested page directly, but it results in an empty object instead of the content from the /foo/[slug]
page, which suggests that the data is not being loaded properly.
So as @pilchard suggested, the solution was to use a +layout.ts
in the /foo/[slug]
route.
The final structure looked like this (on server as files are being read):
/foo/[slug]/+layout.server.js
/foo/[slug]/+page.svelte
/foo/[slug]/bar/+page.svelte
In the layout file, I created the load function the read the file and output the data. In the foo
page component, I use the data initially, then in the bar
page component, you can just use export let data
to get the data from the parent layout. This does not call the load
function twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With