How to create a persistent variable in Sveltekit using Local Storage?

peterking1697923543 peterking1697923543
Blog
How to create a persistent variable in Sveltekit using Local Storage?


<script>
  import { writable } from 'svelte/store';

  // Create a writable store with an initial value
  const name = writable('Svelte');

  // Check if localStorage has a value for name
  if (localStorage.getItem('name')) {
    // If yes, set the store value to the localStorage value
    name.set(localStorage.getItem('name'));
  }

  // Subscribe to changes in the store value
  name.subscribe((value) => {
    // Update the localStorage with the new value
    localStorage.setItem('name', value);
  });
</script>

<h1>Hello, {$name}!</h1>
<input type="text" bind:value={$name} />

Comments (0)

U
Press Ctrl+Enter to post

No comments yet

Be the first to share your thoughts!