0
0
SvelteHow-ToBeginner · 3 min read

How to Update Store Value in Svelte: Simple Guide

In Svelte, you update a store value by using the update or set methods on a writable store. Use store.set(newValue) to replace the value or store.update(callback) to change it based on the current value.
📐

Syntax

Svelte provides writable stores with two main methods to update their values:

  • set(newValue): Replaces the current store value with newValue.
  • update(callback): Takes a function that receives the current value and returns the new value.

This allows simple or computed updates to the store.

javascript
import { writable } from 'svelte/store';

const count = writable(0);

// Replace value
count.set(5);

// Update value based on current
count.update(n => n + 1);
💻

Example

This example shows a counter that updates its store value when a button is clicked. It uses update to increment the count.

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

  const count = writable(0);

  function increment() {
    count.update(n => n + 1);
  }
</script>

<button on:click={increment} aria-label="Increment count">Count: {$count}</button>
Output
A button labeled "Count: 0" that increments the number each time it is clicked.
⚠️

Common Pitfalls

Common mistakes when updating Svelte stores include:

  • Trying to assign a value directly to the store variable instead of using set or update.
  • Not subscribing to the store or using the $ prefix to access its value in components.
  • Using update without returning a new value from the callback.

Always use set or update methods to change store values.

javascript
import { writable } from 'svelte/store';

const count = writable(0);

// Wrong: Direct assignment (does not update store)
// count = 5;

// Right: Use set method
count.set(5);

// Wrong: update callback missing return
// count.update(n => { n + 1 }); // returns undefined

// Right: update callback returns new value
count.update(n => n + 1);
📊

Quick Reference

MethodDescriptionUsage Example
setReplaces the store valuecount.set(10)
updateUpdates value based on currentcount.update(n => n + 1)
$ prefixAccess store value in componentCount: {$count}

Key Takeaways

Use writable stores' set() to replace values and update() to change values based on current state.
Always return a new value from the update() callback function.
Access store values in components with the $ prefix for automatic subscription.
Never assign directly to the store variable; use set() or update() methods.
Remember to handle store updates in event handlers or reactive statements.