Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Loading data only once in Svelte Kit and when to use page.js vs layout.js for loading data

$
0
0

I have two questions related to SvelteKit, the first one is:

1. How to load data only on the first page load?

I'm currently loading some global data from my layout.js file, such as user information. Since I'm using client side routing, this should only need to be loaded on the first page load, and not on each navigation which it seems to be doing now.

layout.js

import { api } from '$lib/api';export const prerender = true;/**  * @type {import('./$types').LayoutLoad} * @return {Promise<Record<string,[]|string>>} */export async function load({ fetch, params }) {    // ...    const [userRes] = await Promise.all([        api.get(fetch, `/user`),    ]);    return {        user: userRes.status === 200 ? await userRes.json() : [],    }}

Is there an alternative to this, which would only run on the first page load?

2. When to use layout.js vs page.js, does it impact performance?

Currently I'm loading the global data in layout.js, and I'm loading the individual page data in page.js. Does this have any impact on performance? Does page.js run after layout.js? In that case, if SSR is disabled, the page should load faster if the page data is also loaded as an asynchronous API call together with the other API calls?

Is there are reason that not all data should be loaded in the same file, or does it impact performance at all? Would appreciate any input and information on that part.


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>