Skip to content

Instantly share code, notes, and snippets.

@sharu725
Last active November 26, 2023 18:32
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharu725/b47c5bbd13d49b12e9b8760effae2595 to your computer and use it in GitHub Desktop.
Save sharu725/b47c5bbd13d49b12e9b8760effae2595 to your computer and use it in GitHub Desktop.
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
Copy link

@mef
Copy link

mef commented Mar 9, 2022

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).

@sharu725
Copy link
Author

sharu725 commented Mar 9, 2022

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