Categories
Javascript Svelte

Svelte stores in localStorage

Svelte stores are great for managing state in an application but when combined with modern browser features. they really shine. Let’s take a look at how I implemented localStorage in a recent project with an annotated sample file:

$stores/local.js

import { browser } from '$app/environment';
import { writable } from 'svelte/store';
// it works with readable stores too!

// create an object w/default values
let goals = {
  goal1: 2000,
  goal2: 50
};

// ensure this only runs in the browser
if (browser) {
  // if the object already exists in localStorage, get it
  // otherwise, use our default values
  goals = JSON.parse(localStorage.getItem('goals')) || goals;
}

// export the store for usage elsewhere
export const goalStore = writable(goals);

if (browser) {
  // update localStorage values whenever the store values change
  goalStore.subscribe((value) =>
    // localStorage only allows strings
    // IndexedDB does allow for objects though... 🤔
    localStorage.setItem('goals', JSON.stringify(value))
  );
}

Throughout the rest of the app, the “goalStore” (and therefore, the localStorage object) can be accessed by importing in components like so:

<script>
    import { goalStore } from '$stores/local';
</script>

<!-- use '$' for reactivity and 'bind:' to keep data upstream in sync -->
<Component bind:count={$goalStore.goal1} />

I hope this helps someone! If you’d like to see how I implemented this in its entirety, you can view the source code here.

By Dylan Hildenbrand

10+ years experience in web development, homelab enthusiast, tinkerer

profile for Dylan Hildenbrand on Stack Exchange, a network of free, community-driven Q&A sites  

Do you like these posts? Consider sponsoring me or making a donation!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.