w# Svelte Reusable Reactive Logic Proof of Concept

This project demonstrates a pattern for creating reusable reactive logic in Svelte using a name.svelte.ts file.

Code Explanation

The core of this pattern lies in the src/lib/kitLoader.svelte.ts file. Let's break down the code:

  • LoadingState Enum: Defines the possible states of the data loading process (Idle, Loading, Loaded, Error).

    enum LoadingState {
        Loading = "loading",
        Loaded = "loaded",
        Error = "error",
        Idle  = "idle"
    }
    
  • KitItem Interface: Defines the structure of a kit item.

    export interface KitItem {
        kitNo: string
    }
    
  • KitListLoadier Class: This class encapsulates the reactive logic for loading a list of KitItem objects.

    class KitListLoadier {
    
        loadingState = $state(LoadingState.Idle)
        loadedKIts = $state<KitItem[]>([])
    
        private async _load() {
            console.log("loading kits")
            this.loadingState = LoadingState.Loading
            await new Promise((resolve) => setTimeout(resolve, 1000))
            this.loadedKIts = [
                { kitNo: "123" },
                { kitNo: "456" },
            ]
            this.loadingState = LoadingState.Loaded
        }
    
        load() {
            this._load()
        }
    
    }
    
  • kitListLoader Instance: A single instance of the KitListLoadier class is created and exported.

    let kitListLoader = new KitListLoadier()
    export { kitListLoader }
    

The +page.svelte file then imports and uses the kitListLoader instance:

  • It displays the current loadingState.

  • It provides a button that, when clicked, calls the load() method on the kitListLoader instance.

  • It displays the loadedKIts array as a JSON string.

    <script lang="ts">
        import { kitListLoader } from '$lib/kitLoader.svelte'
    
    </script>
    
    <h1>home</h1>
    
    <div>loading state {kitListLoader.loadingState}</div>
    
    <button onclick={() => kitListLoader.load()}>load</button>
    
    <pre>
    {JSON.stringify(kitListLoader.loadedKIts, null, 2)}
    </pre>
    

Why This Works and Demonstrates Reusability

  1. Encapsulation: The KitListLoadier class encapsulates all the logic related to loading and managing the list of kits. This makes the code more organized and easier to understand.

  2. Reactivity: The $state variables ensure that the UI is automatically updated whenever the loadingState or loadedKIts values change.

  3. Single Instance: By exporting a single instance of the KitListLoadier class, we ensure that all components that import kitListLoader share the same reactive state. This is crucial for maintaining consistency across the application.

  4. .svelte.ts Pattern: The use of a .svelte.ts file allows us to define the reactive logic in a separate file, keeping the Svelte component file clean and focused on the UI.

Proof of Reusability

This pattern is reusable because you can create similar name.svelte.ts files for other data loading scenarios. You can adapt the KitListLoadier class to load different types of data from different sources, and you can use the same pattern of exporting a single instance to share the reactive state across your application.

To reuse this pattern:

  1. Create a new name.svelte.ts file in the $lib directory.
  2. Define a class similar to KitListLoadier that encapsulates the logic for loading and managing your data.
  3. Create a single instance of your class and export it.
  4. Import the instance into your Svelte components and use its reactive state variables and methods.

Top categories

svelte logo

Need a Svelte website built?

Hire a professional Svelte developer today.
Loading Svelte Themes