How to write persist in svelte?

674 Views Asked by At

I need to convert my store to a persisting store that uses a Localstorage to hold my data even if the user closes the browser. I have tried writing the code using Localstorage.setItem and getItem but unfortunately, It doesn't work properly. Can someone help me to write it in a proper way?

This is my code in App.svelte file

<script>
const storeInputFromUser = () => {
userId = Math.random();
let inputData = {
  id: userId,
  title: inputTitle, /* here I am taking input from input field. It works fine */
  text: inputText, /* here I am taking input from input field. It works fine */
};
inputTitle = '';
inputText = '';
database = [inputData, ...database];
DataStore.update(() => {
  return database;
});
</script>


//DataStore.js

import { writable } from "svelte/store";

const DataStore = writable(JSON.parse(localStorage.getItem("data")) || {});
DataStore.subscribe(value => {
    localStorage.setItem("data", JSON.stringify(value));
    console.log(value);
});

export default DataStore;

This code can save data into the local storage but when I click refresh, the DIV I use to show the data becomes empty. The local storage still has the data

0

There are 0 best solutions below