Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist svelte store

Is there any direct option to persist svelte store data so that even when the page is refreshed, data will be available.

I am not using local storage since I want the values to be reactive.

like image 857
Anil Sivadas Avatar asked Jun 07 '19 05:06

Anil Sivadas


People also ask

How do you persist shop in svelte?

You can manually create a subscription to your store and persist the changes to localStorage and also use the potential value in localStorage as default value. @AnilSivadas Doing it on the server complicates it a bit. You could skip it on the server and just do it in the browser with a typeof window !==

How do I use localStorage in svelte?

Create the store All we need to do to connect to local storage is create a writable store and then set a default value based on local storage and on any change (via subscribe ) we update the local storage entry.


1 Answers

You can manually create a subscription to your store and persist the changes to localStorage and also use the potential value in localStorage as default value.

Example

<script>   import { writable } from "svelte/store";   const store = writable(localStorage.getItem("store") || "");    store.subscribe(val => localStorage.setItem("store", val)); </script>  <input bind:value={$store} /> 
like image 100
Tholle Avatar answered Sep 20 '22 15:09

Tholle