Skip to content

Instantly share code, notes, and snippets.

@danybeltran
Created March 27, 2024 17:02
Show Gist options
  • Save danybeltran/e01baf55fd40f56d2a94d797ebe27916 to your computer and use it in GitHub Desktop.
Save danybeltran/e01baf55fd40f56d2a94d797ebe27916 to your computer and use it in GitHub Desktop.
Create a Writable localStorage store that allows both updating and reading by subscription
import { writable } from 'svelte/store'
const storedKeys: any = {}
/**
* Create a Writable localStorage store that allows both updating and reading by subscription
*/
export function storable<T>(initialValue: T) {
const storedKey = `$-${Object.keys(storedKeys).length}`
storedKeys[storedKey] = true
const store = writable(initialValue)
try {
store.set(JSON.parse(localStorage.getItem(storedKey)!) || initialValue)
store.subscribe(value => {
localStorage.setItem(storedKey, JSON.stringify(value || initialValue))
})
} catch {}
return store
}
@danybeltran
Copy link
Author

Example usage:

<script>

  import { storable } from '$lib/storable.ts'

  // Value will be immediately available when page loads
  let email = storable('')

</script>

<div class="space-y-4">
  <input type="text" bind:value={$email} />
</div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment