Sveltekit - Advanced Loading



Advanced loading in SvelteKit uses different load functions to efficiently handle data fetching and component rendering. This chapter gives a brief overview of these load functions and their features, including Universal load functions, how to use both load functions together, accessing data from parent components, techniques for data invalidation, creating custom dependencies, and the invalidateAll method.

Universal Load Functions

Universal load functions can work on both the server during server-side rendering and in the browser during client-side navigation. This provides flexibility that allows you to return values that can't be easily converted into a simple format, like components or stores.

Syntax Example

You can define your universal load function in a file named +page.js or +layout.js within your route directory. This file will contain the logic for fetching data.

// src/routes/red/+page.js
export function load() {
    return { component: RedComponent }; // Return a component constructor
}

Using Both Load Functions

Sometimes, you need to use server load functions together with universal load functions. This is helpful when you want to get data from the server and also return values that can't be easily converted, like components or stores.

Syntax Example

You can access the server data in a universal load function as mentioned below:

// src/routes/+page.js
export async function load({ data }) {
    const module = data.old ? await import('./OldComponent.svelte') : await import('./NewComponent.svelte');
    return { component: module.default, message: data.message };
}

Using Parent Data

You can access data from parent load functions by using await parent(). This is helpful when you want to combine data from different sources.

Syntax Example

To can access the parent data using await parent() in the following way:

// src/routes/sum/+layout.js
export async function load({ parent }) {
    const { a, b } = await parent(); 
    return { c: a + b }; // Calculate c
}

Invalidation

SvelteKit allows you to invalidate data and reload specific routes or components when certain conditions happen. This is important for making sure that users always see the latest information.

You can use invalidate('/some-route') to refresh specific data when an action occurs.

Custom Dependencies

You can create custom dependencies for your load functions, which allows you to decide when they should get new data based on certain conditions or events.

Invalidate All

To refresh all the data in your application, you can use invalidateAll(). This will reload all routes and components that depends on any of the data that has been marked as outdated.

Using InvalidateAll

To use invalidateAll in SvelteKit, follow these steps:

  • First, you need to import the invalidateAll function from $app/navigation in your Svelte component.
<script>
    import { invalidateAll } from '$app/navigation';
</script>
  • Then, you can call invalidateAll() whenever you want to refresh all load functions for the current page. For example:
  • <button on:click={invalidateAll}>Reload Data</button>

    Example

    The following is a simple example of using InvalidateAll function in SvelteKit. The below example is reloading the data and updating the timestamp when the refresh button is clicked.

    <!--src/routes/+page.server.js-->
    export function load() {
        return {
            message: "Welcome to SvelteKit",
            time: new Date().toLocaleTimeString(),
            items: [
                { id: 1, text: "First Item" },
                { id: 2, text: "Second Item" }
            ]
        };
    }
    
    <!--src/routes/+page.svelte-->
    <script>
        import { invalidate } from '$app/navigation';
        export let data;
    
        async function refreshData() {
            location.reload(); // Simple but effective way to refresh
        }
    </script>
    
    <div class="container">
        <h1>{data.message}</h1>
        <p>Last loaded: {data.time}</p>
        
        <ul>
            {#each data.items as item}
                <li>{item.text}</li>
            {/each}
        </ul>
    
        <button on:click={refreshData}>Refresh Data</button>
    </div>
    
    <style>
        .container {
            padding: 20px;
            max-width: 600px;
            margin: 0 auto;
        }
        ul {
            margin: 20px 0;
        }
    </style>

    Output

    Sveltekit-advanced-loading
    Advertisements