Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Derived Stores | Stores and Shared State
Introduction to Svelte

Derived Stores

Свайпніть щоб показати меню

Sometimes application data depends on other pieces of state. Instead of manually recalculating values every time something changes, Svelte allows developers to create derived stores.

Derived stores automatically generate new values based on existing stores.

What Are Derived Stores?

A derived store is a reactive store whose value is calculated from one or more other stores.

For example, a shopping cart application may calculate:

  • Total item count;
  • Final price;
  • Discounted price;
  • Tax totals.

These values can update automatically whenever the original store data changes.

Creating a Derived Store

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

Add the following code:

import { writable, derived } from 'svelte/store';

export const cartItems = writable(3);

export const totalPrice = derived(
  cartItems,
  ($cartItems) => $cartItems * 20
);

The derived() function creates a new store based on another store.

In this example, the total price updates automatically whenever the number of cart items changes.

Using the Derived Store

Open App.svelte and import the stores:

<script>
  import { cartItems, totalPrice } from './stores/cartStore.js';
</script>

<h2>Items: {$cartItems}</h2>
<h2>Total: ${$totalPrice}</h2>

<button on:click={() => $cartItems += 1}>
  Add Item
</button>

Each time the item count changes, the total price updates automatically.

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 3

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 4. Розділ 3
some-alt