StorageInteractivity
useLocalStorage
A hook that syncs state with the localStorage, making it easy to persist data across page reloads.
Parameters
Name | Type | Description |
---|---|---|
initialValue | number, string | The initial value you would like to be stored if there are no existing stores matching this key. |
Return Values
Name | Type | Description |
---|---|---|
store.value | any | Returns the current count value. The |
Source Code
import { onMount } from 'svelte'; const useLocalStorage = (key, initialValue) => { let value = $state(initialValue); onMount(() => { const currentValue = localStorage.getItem(key); if (currentValue) value = JSON.parse(currentValue); }); const save = () => { if (value) { localStorage.setItem(key, JSON.stringify(value)); } else { localStorage.removeItem(key); } }; return { get value() { return value; }, set value(v) { value = v; save(); }, }; }; export default useLocalStorage;
<script> import useLocalStorage from './useLocalStorage.svelte.js'; const store = useLocalStorage('secret'); const reset = () => { store.value = null; }; const refresh = () => { window.location.reload(); }; </script> <div class="container"> <div class="input-container"> <input type="text" bind:value={store.value} placeholder="Tell me a secret..." /> </div> <div class="buttons"> <button class="neutral" type="button" on:click={refresh}> Refresh </button> <button class="red" type="button" disabled={!store.value} on:click={reset}>Clear Storage</button> </div> </div> <style> .container { display: flex; flex-direction: column; align-items: center; gap: 15px; } .input-container { display: flex; gap: 10px; } .buttons { display: flex; gap: 15px; } </style>