Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Writable Stores | Stores and Shared State
Introduction to Svelte

Writable Stores

Swipe um das Menü anzuzeigen

Writable stores are the most common type of store in Svelte. They allow components to both read and update shared state.

This makes writable stores useful for managing dynamic application data such as counters, shopping carts, user settings, and notifications.

Creating a Writable Store

Inside the stores folder, create a file called themeStore.js.

Add the following code:

import { writable } from 'svelte/store';

export const theme = writable('light');

The writable() function creates a reactive store whose value can change over time.

In this example, the initial theme value is "light".

Accessing Store Values

Open App.svelte and import the store:

<script>
  import { theme } from './stores/themeStore.js';
</script>

<h2>Current Theme: {$theme}</h2>

The $theme syntax automatically subscribes to the store and displays its current value.

Updating the Store

Writable stores can be updated directly inside the component.

<button on:click={() => $theme = 'dark'}>
  Switch to Dark Mode
</button>

When the button is clicked, the store value changes and the interface updates automatically.

Using Store Methods

Stores also include built-in methods like set() and update().

theme.set('dark');

The update() method is useful when changing values based on the current state.

count.update(value => value + 1);

These methods are commonly used in larger applications and reusable store logic.

question mark

What is the main purpose of a writable store in Svelte?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 4. Kapitel 2

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 4. Kapitel 2
some-alt