Skip to main content

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:

stores.js
export const elapsed = derived(
	time,
	($time) => Math.round(($time - start) / 1000)
);

It's possible to derive a store from multiple input stores, and to explicitly set a value instead of returning it (which is useful for deriving values asynchronously). Consult the API reference for more information.

Next: Custom stores

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script>
	import { time, elapsed } from './stores.js';
 
	const formatter = new Intl.DateTimeFormat(
		'en',
		{
			hour12: true,
			hour: 'numeric',
			minute: '2-digit',
			second: '2-digit'
		}
	);
</script>
 
<h1>The time is {formatter.format($time)}</h1>
 
<p>
	This page has been open for
	{$elapsed}
	{$elapsed === 1 ? 'second' : 'seconds'}
</p>
 
initialising