-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Description
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
optionsobject with a singletranscoder/serializerproperty 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