You can create a store whose value is based on the value of one or more other stores with derived
. Building on our previous example, we can create a store that derives the time the page has been open:
export const elapsed = derived(
time,
$time => Math.round(($time - start) / 1000)
);
It's possible to derive a store from multiple inputs, and to explicitly
set
a value instead of returning it (which is useful for deriving values asynchronously). Consult the API reference for more information.
App.svelte
stores.js
xxxxxxxxxx
17
1
<script>
2
import { time, elapsed } from './stores.js';
3
4
const formatter = new Intl.DateTimeFormat('en', {
5
hour12: true,
6
hour: 'numeric',
7
minute: '2-digit',
8
second: '2-digit'
9
});
10
</script>
11
12
<h1>The time is {formatter.format($time)}</h1>
13
14
<p>
15
This page has been open for
16
{$elapsed} {$elapsed === 1 ? 'second' : 'seconds'}
17
</p>
Console
xxxxxxxxxx
94
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
component_subscribe,
6
detach,
7
element,
8
init,
9
insert,
10
noop,
11
safe_not_equal,
12
set_data,
13
space,
14
text
15
} from "svelte/internal";
16
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */