banjocode A Persistent Svelte Store With Localstorage

A Persistent Svelte Store With Localstorage

Storing data in localstorage is very common in most web applications, this is a neat trick to do that with a Svelte Store

2 min read

A persistent Svelte store

It’s not uncommon to want to save your state in localstorage. I found this neat trick here that allows you to easily create a Svelte store with a function you can call to save and load your state in localStorage.

This is a basic example with a counter.

// store.js
import { writable } from 'svelte/store';

const createWritableStore = (key, startValue) => {
  const { subscribe, set } = writable(startValue);
  
	return {
    subscribe,
    set,
    useLocalStorage: () => {
      const json = localStorage.getItem(key);
      if (json) {
        set(JSON.parse(json));
      }
      
      subscribe(current => {
        localStorage.setItem(key, JSON.stringify(current));
      });
    }
  };
}

export const count = createWritableStore('count', 0);

And you simply use it by importing it and calling the useLocalStorage method if you want to activate it.

// App.svelte
import { count } from 'store.js';

count.useLocalStorage();