Last active
November 26, 2023 18:32
-
-
Save sharu725/b47c5bbd13d49b12e9b8760effae2595 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { writable } from "svelte/store"; | |
import { browser } from "$app/environment"; | |
//string | |
export const userName = writable( | |
(browser && localStorage.getItem("userName")) || "hello world" | |
); | |
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: "username", | |
id: "123", | |
}; | |
export const user = writable(browser && storedUser); | |
user.subscribe( | |
(val) => browser && (localStorage.user = JSON.stringify(val)) | |
); |
Manndung75
commented
Aug 16, 2021
Nice one, thanks.
In the snippet above, the stores don't get an initial default value set during server-side rendering.
Changing the brackets location ensures that a default value is set at page load:
export const userName = writable(
(browser && localStorage.getItem("userName")) || "webjeda"
);
(remark: technically, the brackets are not even needed).
Nice one, thanks.
In the snippet above, the stores don't get an initial default value set during server-side rendering.
Changing the brackets location ensures that a default value is set at page load:
export const userName = writable( (browser && localStorage.getItem("userName")) || "webjeda" );
(remark: technically, the brackets are not even needed).
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment