Skip to content

Reactive LocalStorage/SessionStorage classes #15886

@WarningImHack3r

Description

@WarningImHack3r

Describe the problem

Dealing with localStorage is something I find myself doing quite often, be it for storing user settings, augmenting the user experience by storing some state, and so on.

Many libraries and snippets online provide different implementations for that, but they all have their drawbacks: massive to implement, not "properly optimized" — using $effect.root and/or throwing outside the browser —, not being compatible with Svelte 5, missing some features, not reacting on localStorage changes but only on state change, and so on.

I think such a class should be part of Svelte, especially motivated by the presence of other such utility classes like MediaQuery. Leveraging browser standards, an implementation by Svelte itself would benefit from cleaner and proper lifecycle management, and would be made "the right way" with all the necessary features, nothing more, nothing less.

Describe the proposed solution

Two classes: LocalStorage and SessionStorage, exported from svelte/reactivity. Both would potentially derive from a parent class or interface, exported or not, to keep both implementations on the right path. We could also imagine this parent structure as a backbone for another storage system like Cookie or any user-extendable implementation.

Both would have the same signature:

export class LocalStorage<T> {
    constructor(key: string, defaultValue?: T | undefined) {} // no default value = nothing is set at instantiation, updates begin after a call to the setter or an external localStorage update

    get current(): T {
        // returns the reactive, up-to-date localStorage value
    }

    set current(value: T) {
        // update the localStorage value
    }
}

Implementations would feature:

  • Proactive updates provided by the browser's storage event
  • Use devalue as a serializer/transcoder
  • A potential third parameter that would be either:
    • (Preferred) a SvelteKit transporter to use another encoder/decoder than devalue, like JSON (for some reason)
    • A minimal options object with a single transcoder/serializer property that uses the previous point above and is future-proof
  • A natural lifecycle management that plugs into components, supports SSR, and works (is inert) on the server

Importance

would make my life easier

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions