メインコンテンツへスキップ

ストア

ストアとは、シンプルなストアコントラクトを介して値へのリアクティブなアクセスを可能にするオブジェクトです。 svelte/storeモジュールには、このコントラクトを満たす最小限のストア実装が含まれています。

ストアへの参照がある場合、コンポーネント内で$文字をプレフィックスとして付けることで、その値にアクセスできます。これにより、Svelteはプレフィックス付きの変数を宣言し、コンポーネントの初期化時にストアを購読し、適切なタイミングで購読を解除します。

$プレフィックス付きの変数への代入には、その変数が書き込み可能なストアである必要があります。代入は、ストアの.setメソッドの呼び出しになります。

ストアは、コンポーネントの最上位レベルで宣言する必要があります(例:ifブロックや関数内ではありません)。

(ストアの値を表さない)ローカル変数には、$プレフィックスを付けてはなりません。

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

	const count = writable(0);
	console.log($count); // logs 0

	count.set(1);
	console.log($count); // logs 1

	$count = 2;
	console.log($count); // logs 2
</script>

ストアを使用するケース

Svelte 5以前は、ストアはコンポーネント間のリアクティブな状態の作成やロジックの抽出のための主要なソリューションでした。ルーンを使用することで、これらのユースケースは大幅に減少しました。

  • ロジックを抽出する場合、ルーンの普遍的なリアクティビティを利用する方が優れています。ルーンはコンポーネントの最上位レベル以外でも使用でき、JavaScriptまたはTypeScriptファイル(.svelte.jsまたは.svelte.tsファイルの拡張子を使用)に配置することもできます。
  • 共有状態を作成する場合、必要な値を含む$stateオブジェクトを作成し、その状態を操作できます。
state.svelte
export const 
const userState: {
    name: string;
}
userState
=
function $state<{
    name: string;
}>(initial: {
    name: string;
}): {
    name: string;
} (+1 overload)
namespace $state

Declares reactive state.

Example:

let count = $state(0);

https://svelte.dokyumento.jp/docs/svelte/$state

@paraminitial The initial value
$state
({
name: stringname: 'name', /* ... */ });
App
<script>
	import { userState } from './state.svelte';
</script>

<p>User name: {userState.name}</p>
<button onclick={() => {
	userState.name = 'new name';
}}>
	change name
</button>

複雑な非同期データストリームがある場合、または値の更新や変更のリスニングに対してより手動で制御することが重要な場合、ストアは依然として優れたソリューションです。RxJsに精通していてその知識を再利用したい場合にも、$は便利です。

svelte/store

svelte/storeモジュールには、ストアコントラクトを満たす最小限のストア実装が含まれています。外部から更新できるストア、内部からのみ更新できるストア、およびストアを組み合わせたり派生させるためのメソッドを提供します。

writable

コンポーネントの「外部」から設定できる値を持つストアを作成する関数です。追加のsetメソッドとupdateメソッドを持つオブジェクトとして作成されます。

setは、設定する値を1つの引数として取るメソッドです。ストアの値が既にそれと等しくない場合、ストアの値は引数の値に設定されます。

updateは、コールバックを1つの引数として取るメソッドです。コールバックは既存のストアの値を引数として取り、ストアに設定する新しい値を返します。

store
import { function writable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Writable<T>

Create a Writable store that allows both updating and reading by subscription.

@paramvalue initial value
writable
} from 'svelte/store';
const const count: Writable<number>count = writable<number>(value?: number | undefined, start?: StartStopNotifier<number> | undefined): Writable<number>

Create a Writable store that allows both updating and reading by subscription.

@paramvalue initial value
writable
(0);
const count: Writable<number>count.Readable<number>.subscribe(this: void, run: Subscriber<number>, invalidate?: () => void): Unsubscriber

Subscribe on value changes.

@paramrun subscription callback
@paraminvalidate cleanup callback
subscribe
((value: numbervalue) => {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
(value: numbervalue);
}); // logs '0' const count: Writable<number>count.Writable<number>.set(this: void, value: number): void

Set value and inform subscribers.

@paramvalue to set
set
(1); // logs '1'
const count: Writable<number>count.Writable<number>.update(this: void, updater: Updater<number>): void

Update value using callback and inform subscribers.

@paramupdater callback
update
((n: numbern) => n: numbern + 1); // logs '2'

関数が2番目の引数として渡された場合、購読者の数が0から1に増加したときに呼び出されます(ただし、1から2などには呼び出されません)。その関数は、ストアの値を変更するset関数と、ストアの新しい値を古い値から計算するコールバックを取るupdate関数(ストアのupdateメソッドのように動作します)を渡されます。購読者数が1から0に減少したときに呼び出されるstop関数を返す必要があります。

store
import { function writable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Writable<T>

Create a Writable store that allows both updating and reading by subscription.

@paramvalue initial value
writable
} from 'svelte/store';
const const count: Writable<number>count = writable<number>(value?: number | undefined, start?: StartStopNotifier<number> | undefined): Writable<number>

Create a Writable store that allows both updating and reading by subscription.

@paramvalue initial value
writable
(0, () => {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
('got a subscriber');
return () => var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
('no more subscribers');
}); const count: Writable<number>count.Writable<number>.set(this: void, value: number): void

Set value and inform subscribers.

@paramvalue to set
set
(1); // does nothing
const const unsubscribe: Unsubscriberunsubscribe = const count: Writable<number>count.Readable<number>.subscribe(this: void, run: Subscriber<number>, invalidate?: () => void): Unsubscriber

Subscribe on value changes.

@paramrun subscription callback
@paraminvalidate cleanup callback
subscribe
((value: numbervalue) => {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
(value: numbervalue);
}); // logs 'got a subscriber', then '1' const unsubscribe: () => voidunsubscribe(); // logs 'no more subscribers'

writableの値は、ページのリフレッシュなど、破棄されると失われます。ただし、値を例えばlocalStorageに同期させる独自のロジックを作成できます。

readable

値を「外部」から設定できないストアを作成します。最初の引数はストアの初期値で、readableへの2番目の引数はwritableへの2番目の引数と同じです。

import { function readable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Readable<T>

Creates a Readable store that allows reading by subscription.

@paramvalue initial value
readable
} from 'svelte/store';
const const time: Readable<Date>time = readable<Date>(value?: Date | undefined, start?: StartStopNotifier<Date> | undefined): Readable<Date>

Creates a Readable store that allows reading by subscription.

@paramvalue initial value
readable
(new
var Date: DateConstructor
new () => Date (+4 overloads)
Date
(), (set: (value: Date) => voidset) => {
set: (value: Date) => voidset(new
var Date: DateConstructor
new () => Date (+4 overloads)
Date
());
const const interval: NodeJS.Timeoutinterval = function setInterval<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)

Schedules repeated execution of callback every delay milliseconds.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setInterval().

@sincev0.0.1
@paramcallback The function to call when the timer elapses.
@paramdelay The number of milliseconds to wait before calling the callback.
@paramargs Optional arguments to pass when the callback is called.
@returnfor use with {@link clearInterval}
setInterval
(() => {
set: (value: Date) => voidset(new
var Date: DateConstructor
new () => Date (+4 overloads)
Date
());
}, 1000); return () => function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void (+1 overload)

Cancels a Timeout object created by setInterval().

@sincev0.0.1
@paramtimeout A Timeout object as returned by {@link setInterval} or the primitive of the Timeout object as a string or a number.
clearInterval
(const interval: NodeJS.Timeoutinterval);
}); const const ticktock: Readable<string>ticktock = readable<string>(value?: string | undefined, start?: StartStopNotifier<string> | undefined): Readable<string>

Creates a Readable store that allows reading by subscription.

@paramvalue initial value
readable
('tick', (set: (value: string) => voidset, update: (fn: Updater<string>) => voidupdate) => {
const const interval: NodeJS.Timeoutinterval = function setInterval<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)

Schedules repeated execution of callback every delay milliseconds.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setInterval().

@sincev0.0.1
@paramcallback The function to call when the timer elapses.
@paramdelay The number of milliseconds to wait before calling the callback.
@paramargs Optional arguments to pass when the callback is called.
@returnfor use with {@link clearInterval}
setInterval
(() => {
update: (fn: Updater<string>) => voidupdate((sound: stringsound) => (sound: stringsound === 'tick' ? 'tock' : 'tick')); }, 1000); return () => function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void (+1 overload)

Cancels a Timeout object created by setInterval().

@sincev0.0.1
@paramtimeout A Timeout object as returned by {@link setInterval} or the primitive of the Timeout object as a string or a number.
clearInterval
(const interval: NodeJS.Timeoutinterval);
});

derived

1つ以上の他のストアからストアを派生させます。コールバックは、最初の購読者が購読したときに最初に実行され、ストアの依存関係が変更されるたびに実行されます。

最も単純なバージョンでは、derivedは単一のストアを取り、コールバックは派生値を返します。

import { function derived<S extends Stores, T>(stores: S, fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void, initial_value?: T | undefined): Readable<T> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
} from 'svelte/store';
const const doubled: Readable<number>doubled = derived<Writable<number>, number>(stores: Writable<number>, fn: (values: number) => number, initial_value?: number | undefined): Readable<number> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
(const a: Writable<number>a, ($a: number$a) => $a: number$a * 2);

コールバックは、2番目の引数setとオプションの3番目の引数updateを受け入れることで、非同期的に値を設定できます。必要に応じて、どちらか一方または両方を実行します。

この場合、derivedに3番目の引数(setまたはupdateが最初に呼び出される前の派生ストアの初期値)を渡すこともできます。初期値が指定されていない場合、ストアの初期値はundefinedになります。

import { function derived<S extends Stores, T>(stores: S, fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void, initial_value?: T | undefined): Readable<T> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
} from 'svelte/store';
const const delayed: Readable<number>delayed = derived<Writable<number>, number>(stores: Writable<number>, fn: (values: number, set: (value: number) => void, update: (fn: Updater<number>) => void) => Unsubscriber | void, initial_value?: number | undefined): Readable<...> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
(
const a: Writable<number>a, ($a: number$a, set: (value: number) => voidset) => { function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)

Schedules execution of a one-time callback after delay milliseconds.

The callback will likely not be invoked in precisely delay milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setTimeout().

@sincev0.0.1
@paramcallback The function to call when the timer elapses.
@paramdelay The number of milliseconds to wait before calling the callback.
@paramargs Optional arguments to pass when the callback is called.
@returnfor use with {@link clearTimeout}
setTimeout
(() => set: (value: number) => voidset($a: number$a), 1000);
}, 2000 ); const const delayedIncrement: Readable<unknown>delayedIncrement = derived<Writable<number>, unknown>(stores: Writable<number>, fn: (values: number, set: (value: unknown) => void, update: (fn: Updater<unknown>) => void) => Unsubscriber | void, initial_value?: unknown): Readable<...> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
(const a: Writable<number>a, ($a: number$a, set: (value: unknown) => voidset, update: (fn: Updater<unknown>) => voidupdate) => {
set: (value: unknown) => voidset($a: number$a); function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)

Schedules execution of a one-time callback after delay milliseconds.

The callback will likely not be invoked in precisely delay milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setTimeout().

@sincev0.0.1
@paramcallback The function to call when the timer elapses.
@paramdelay The number of milliseconds to wait before calling the callback.
@paramargs Optional arguments to pass when the callback is called.
@returnfor use with {@link clearTimeout}
setTimeout
(() => update: (fn: Updater<unknown>) => voidupdate((x: unknownx) => x + 1), 1000);
// every time $a produces a value, this produces two // values, $a immediately and then $a + 1 a second later });

コールバックから関数を返すと、a) コールバックが再び実行されるとき、またはb) 最後の購読者が購読を解除したときに呼び出されます。

import { function derived<S extends Stores, T>(stores: S, fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void, initial_value?: T | undefined): Readable<T> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
} from 'svelte/store';
const const tick: Readable<number>tick = derived<Writable<number>, number>(stores: Writable<number>, fn: (values: number, set: (value: number) => void, update: (fn: Updater<number>) => void) => Unsubscriber | void, initial_value?: number | undefined): Readable<...> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
(
const frequency: Writable<number>frequency, ($frequency: number$frequency, set: (value: number) => voidset) => { const const interval: NodeJS.Timeoutinterval = function setInterval<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)

Schedules repeated execution of callback every delay milliseconds.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setInterval().

@sincev0.0.1
@paramcallback The function to call when the timer elapses.
@paramdelay The number of milliseconds to wait before calling the callback.
@paramargs Optional arguments to pass when the callback is called.
@returnfor use with {@link clearInterval}
setInterval
(() => {
set: (value: number) => voidset(var Date: DateConstructor

Enables basic storage and retrieval of dates and times.

Date
.DateConstructor.now(): number

Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).

now
());
}, 1000 / $frequency: number$frequency); return () => { function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void (+1 overload)

Cancels a Timeout object created by setInterval().

@sincev0.0.1
@paramtimeout A Timeout object as returned by {@link setInterval} or the primitive of the Timeout object as a string or a number.
clearInterval
(const interval: NodeJS.Timeoutinterval);
}; }, 2000 );

どちらの場合も、単一のストアの代わりに、引数の配列を最初の引数として渡すことができます。

import { function derived<S extends Stores, T>(stores: S, fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void, initial_value?: T | undefined): Readable<T> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
} from 'svelte/store';
const const summed: Readable<number>summed = derived<[Writable<number>, Writable<number>], number>(stores: [Writable<number>, Writable<number>], fn: (values: [number, number]) => number, initial_value?: number | undefined): Readable<...> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
([const a: Writable<number>a, const b: Writable<number>b], ([$a: number$a, $b: number$b]) => $a: number$a + $b: number$b);
const const delayed: Readable<unknown>delayed = derived<[Writable<number>, Writable<number>], unknown>(stores: [Writable<number>, Writable<number>], fn: (values: [number, number], set: (value: unknown) => void, update: (fn: Updater<...>) => void) => Unsubscriber | void, initial_value?: unknown): Readable<...> (+1 overload)

Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.

derived
([const a: Writable<number>a, const b: Writable<number>b], ([$a: number$a, $b: number$b], set: (value: unknown) => voidset) => {
function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+2 overloads)

Schedules execution of a one-time callback after delay milliseconds.

The callback will likely not be invoked in precisely delay milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setTimeout().

@sincev0.0.1
@paramcallback The function to call when the timer elapses.
@paramdelay The number of milliseconds to wait before calling the callback.
@paramargs Optional arguments to pass when the callback is called.
@returnfor use with {@link clearTimeout}
setTimeout
(() => set: (value: unknown) => voidset($a: number$a + $b: number$b), 1000);
});

readonly

このシンプルなヘルパー関数は、ストアを読み取り専用にします。この新しい読み取り専用ストアを使用して、元のストアからの変更を購読できます。

import { function readonly<T>(store: Readable<T>): Readable<T>

Takes a store and returns a new one derived from the old one that is readable.

@paramstore - store to make readonly
readonly
, function writable<T>(value?: T | undefined, start?: StartStopNotifier<T> | undefined): Writable<T>

Create a Writable store that allows both updating and reading by subscription.

@paramvalue initial value
writable
} from 'svelte/store';
const const writableStore: Writable<number>writableStore = writable<number>(value?: number | undefined, start?: StartStopNotifier<number> | undefined): Writable<number>

Create a Writable store that allows both updating and reading by subscription.

@paramvalue initial value
writable
(1);
const const readableStore: Readable<number>readableStore = readonly<number>(store: Readable<number>): Readable<number>

Takes a store and returns a new one derived from the old one that is readable.

@paramstore - store to make readonly
readonly
(const writableStore: Writable<number>writableStore);
const readableStore: Readable<number>readableStore.Readable<number>.subscribe(this: void, run: Subscriber<number>, invalidate?: () => void): Unsubscriber

Subscribe on value changes.

@paramrun subscription callback
@paraminvalidate cleanup callback
subscribe
(var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(...data: any[]): void (+1 overload)log);
const writableStore: Writable<number>writableStore.Writable<number>.set(this: void, value: number): void

Set value and inform subscribers.

@paramvalue to set
set
(2); // console: 2
const readableStore: Readable<number>readableStore.set(2); // ERROR

get

一般的に、ストアの値を読み取るには、ストアを購読し、時間の経過とともに変化する値を使用する必要があります。時々、購読していないストアの値を取得する必要がある場合があります。getを使用すると、そうすることができます。

これは、購読を作成し、値を読み取り、購読を解除することによって機能します。したがって、ホットなコードパスでは推奨されません。

import { function get<T>(store: Readable<T>): T

Get the current value from a store by subscribing and immediately unsubscribing.

get
} from 'svelte/store';
const const value: stringvalue = get<string>(store: Readable<string>): string

Get the current value from a store by subscribing and immediately unsubscribing.

get
(const store: Writable<string>store);

ストアコントラクト

store = { subscribe: (subscription: (value: any) => void) => () => undefinedsubscribe: (subscription: (value: any) => voidsubscription: (value: anyvalue: any) => void) => (() => void), set: (value: any) => undefinedset?: (value: anyvalue: any) => void }

svelte/storeに依存せずに、ストアコントラクトを実装することで、独自のストアを作成できます。

  1. ストアには、.subscribeメソッドが含まれている必要があります。このメソッドは、購読関数を受け入れる必要があります。この購読関数は、.subscribeを呼び出したときに、ストアの現在の値ですぐに同期的に呼び出される必要があります。ストアの値が変更されるたびに、ストアのすべてのアクティブな購読関数は後で同期的に呼び出される必要があります。
  2. .subscribeメソッドは、購読解除関数を返す必要があります。購読解除関数を呼び出すと、その購読とそれに対応する購読関数はストアによって再び呼び出されなくなります。
  3. ストアには、オプションで.setメソッドが含まれている場合があります。このメソッドは、ストアの新しい値を引数として受け入れる必要があり、ストアのすべてのアクティブな購読関数を同期的に呼び出します。そのようなストアは、書き込み可能なストアと呼ばれます。

RxJS Observablesとの相互運用性のために、.subscribeメソッドは、購読解除関数を直接返すのではなく、.unsubscribeメソッドを持つオブジェクトを返すこともできます。ただし、.subscribeが購読を同期的に呼び出さない場合(Observable仕様では必須ではありません)、Svelteはストアの値をundefinedと認識します。

GitHubでこのページを編集する