Svelte Perisistent Store!

Svelte store in itself is an amazing feature. What if it was persistent!

svelte logo

Want a Svelte site built?
Hire Me.

Svelte Perisistent Store!

Svelte stores is something I like the most in Svelte. This is because of its simplicity.

Unlike props - which can be passed from parent to child components - stores can be accessed by any component.

This helps in keeping an multi-page app in sync. Also, you can change it from any component to change it across the app.

In some cases, just store isn’t enough. You may want to store it in session or local storage of the browser so that it persists.

A usual use case is dark mode across a website. Once a user chooses dark theme in the hompepage, the app should remain in dark mode on all pages.

I have shown

In Svelte

import { writable } from "svelte/store";

//string
export const userName = writable(localStorage.getItem("userName") || "webjeda");
userName.subscribe((val) => localStorage.userName = val);

// array
const storedFruits = JSON.parse(localStorage.getItem("fruits")) || [
  "apple",
  "orange",
  "grapes",
];
export const fruits = writable(storedFruits);
fruits.subscribe(
  (val) =>localStorage.fruits = JSON.stringify(val)
);

// object
const storedUser = JSON.parse(localStorage.getItem("user") || {
  name: "webjeda",
  id: "123",
};
export const user = writable(storedUser);
user.subscribe((val) => localStorage.user = JSON.stringify(val));

In SvelteKit

import { writable } from "svelte/store";
import { browser } from "$app/env";

//string
export const userName = writable(
  (browser && localStorage.getItem("userName")) || "webjeda"
);
userName.subscribe((val) => browser && (localStorage.userName = val));

// array
const storedFruits = JSON.parse(browser && localStorage.getItem("fruits")) || [
  "apple",
  "orange",
  "grapes",
];
export const fruits = writable(browser && storedFruits);
fruits.subscribe(
  (val) => browser && (localStorage.fruits = JSON.stringify(val))
);

// object
const storedUser = JSON.parse(browser && localStorage.getItem("user")) || {
  name: "webjeda",
  id: "123",
};
export const user = writable(browser && storedUser);
user.subscribe((val) => browser && (localStorage.user = JSON.stringify(val)));

Watch the video here

Find related articles

Let's discuss on Twitter