Initialize store with localstorage data in Svelte

Total
0
Shares

In this article we will quickly learn how to initialize svelte store with localstorage data. All modern browsers have localstorage facility which is used to store data client side.

First of all you should know how to create a store in Svelte. Here is the code for that –

import {writable} from "svelte/store";
let writableStore = writable()

Remember, store files are js files and should end with .js.

Inside writable function, you can pass the default value of store as parameter. So, suppose you want to initialize it with a localstorage data then you can do something like this –

import {writable} from "svelte/store";
let writableStore = writable(localStorage.getItem('key') || 'default value')

Using localstorage with Sapper

Due to the server side rendering feature of Sapper, the localstorage could be a tricky job because server rendered pages do not have localstorage. To tackle this situation, we use process.browser. Check this code –

StoreFile.js

import {writable} from "svelte/store";
export let superhero;
    
if(typeof window !== "undefined") {
  superhero = writable(localStorage.getItem("superhero") || "Hulk");
} else {
  superhero = writable(null);
}

According to this code, when the window is not defined then superhero will be assigned a store with default null. When the window is defined, superhero will get the value from localstorage.

Now we will use this code into a route –

<script>
  import {superhero} from "./StoreFile";
</script>
    
{#if process.browser}
  <p>Current Superhero: {$superhero}</p>
{/if}

Here you can see that we are enclosing the paragraph in if with condition process.browser. This indicates that the block won’t run server side. It will only run at client side where localstorage is available.

    Tweet this to help others

Live Demo

Open Live Demo