javascriptsveltesvelte-5

Loading data server side and allow global access client side


I'm having a hard time understanding the use of Runes and data loading. I load a supabase json file and I want to access the data globally.

// +page.server.js
export async function load() {
    const [_portfolioSummary, error] = await getFullPortfolio('/');
    return _portfolioSummary;
}
// shared.svelte.js
export let portfolioSummary = $state({});
// +page.js
import { portfolioSummary } from '../lib/js/shared.svelte.js';

export async function load({ data }) {
    portfolioSummary = data.portfolioSummary;
}

I get this error:

TypeError: Cannot set property portfolioSummary of #<Object> which has only a getter

What should I do to get portfolioData globally so I can use it anywhere?


Solution

  • You should just directly return the data from a load function.
    It will automatically be available everywhere via a store: $page.data.

    Edit: As of a few minutes ago, there now also is a runes-based version of page in $app/state (@sveltejs/kit@2.12.0).

    If you try to set global variables, you also run the risk of exposing data that belongs to one user to another user (since state on the server is shared between all requests).

    (Exported $state would need to wrap the content in a property, e.g. { current: ... }, then said property can be updated since re-assignments of the import itself are not possible.)