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/environment";
//string
const initialStringValue = "webjeda";
const defaultStringValue = browser
? JSON.parse(window.localStorage.getItem("user_name") || initialStringValue)
: initialStringValue;
export const userName = writable(defaultStringValue);
userName.subscribe((value) => {
if (browser) {
window.localStorage.setItem("user_name", value);
}
});
// array
const initialArrayValue = ["apple", "orange", "grapes"];
const defaultArrayValue = browser
? JSON.parse(
window.localStorage.getItem("fruits") || JSON.stringify(initialArrayValue)
)
: initialArrayValue;
export const fruits = writable(defaultArrayValue);
fruits.subscribe((value) => {
if (browser) {
window.localStorage.setItem("fruits", JSON.stringify(value));
}
});
// object
const initialObjectValue = {
name: "webjeda",
id: "123",
};
const defaultObjectValue = browser
? JSON.parse(
window.localStorage.getItem("user") || JSON.stringify(initialObjectValue)
)
: initialObjectValue;
export const user = writable(defaultObjectValue);
user.subscribe((value) => {
if (browser) {
window.localStorage.setItem("user", JSON.stringify(value));
}
});