Skip to content

Instantly share code, notes, and snippets.

@SpenceDiNicolantonio
Created May 3, 2024 02:19
Show Gist options
  • Save SpenceDiNicolantonio/098f6d30f68d893b4776f054d69bb591 to your computer and use it in GitHub Desktop.
Save SpenceDiNicolantonio/098f6d30f68d893b4776f054d69bb591 to your computer and use it in GitHub Desktop.
Svelte 5 Store to State #svelte #store #typescript
// !! This is yet untested
import type { Writable } from 'svelte/store';
export const toState = <T>(store: Writable<T>, initial: T | null = null) => {
let value = $state<T | null>(initial);
const stateful = {
get: () => value,
set: (newValue: T) => {
store.set(newValue);
value = newValue;
},
subscribe: (run: (value: T) => void) => {
const unsubscribeStore = store.subscribe(run);
return () => unsubscribeStore();
},
};
return stateful;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment