Sync Browser localStorage With Store in Svelte

- 2 minutes read

This is an example writeable Svelte store which is synced with the browser’s localStorage:

/* lib/stores/foo.js */

import { writable } from 'svelte/store';

/* Default store value */
let foo = `bar`;

/* Check for an existing value in localStorage */
if (typeof localStorage !== `undefined`) {
    if (localStorage.getItem(`foo`) !== null) {
        foo = localStorage.getItem(`foo`);
    }
}

/* Set store to default value or localStorage value */
const store = writable(foo);

/* Export store */
export default store;

/* Listen for changes to the store, and update localStorage with the most recent value */
store.subscribe((newValue) => {
    if (typeof localStorage !== `undefined`) {
        localStorage.setItem(`foo`, newValue);
    }
});

Here is an example component that imports the above store:

<!-- lib/components/Example.svelte -->

<script>
    import foo from '$lib/stores/foo';

    let newValue = `bar`;
</script>

Current foo value: {$foo}

<input bind:value={newValue} type="text" />

<button on:click={foo.update(() => newValue)}>
    Update foo
</button>

The above Example.svelte component imports the foo.js store. It includes a simple input and button.

When the button is pressed, the text in the input becomes the new value for the $foo store.

You’ll notice that each time the $foo store is updated, localStorage.foo is updated to the same value.

Link to this section Conclusion

And that is how you sync a store with the browser’s localStorage in Svelte! At least that’s how I typically go about doing it.