Svelte – Custom Stores

1 min read


Hello guysss… welcome back to our channel… Kita masih di materi Svelte ya… karena memang kita mau menyelesaikan dulu materi ini…

edit store.js

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

export const countWritable = writable(0);
export const countAutoSubscriptions = writable(0);

//Readable Store
export const time = readable(new Date(), function start(set) {
	const interval = setInterval(() => {
		set(new Date());
	}, 1000);

	return function stop() {
		clearInterval(interval);
	};
});

//Derived Store
const start = new Date();

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

function createCount() {
	const { subscribe, set, update } = writable(0);

	return {
		subscribe,
		increment: () => update(n => n + 1),
		decrement: () => update(n => n - 1),
		reset: () => set(0)
	};
}

export const countCustom = createCount();

dan tentu kita import ke App.svelte

<main>
	<h1>Hello {name}!</h1>
	<p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
	<Counter />
	<Toggle />
	<Img />
	<String />
	<Statement />
	<Condition />
	<Nested answer={42}/>
	<Nested/>
	<Info {...pkg}/>
	<IfLogin />
	<Comparison />
	<EachYoutube />
	<KeyEachThing />
	<GenerateNumber />
	<MouseMove />
	<MouseMoveInlineHandler />
	<EventModifier />
	<AlertCompEvent />
	<AlertEventForwarding />
	<CustomButtonComp />
	<TextInput />
	<NumericInput />
	<CheckboxInputs />
	<GroupInputs />
	<TextareaInputs />
	<FileInput />
	<SelectBindings />
	<SelectMultiple />
	<EachBlockBindings />
	<MediaElements />
	<Dimensions />
	<BindThisCanvas />
	<ComponentBindings />
	<OnMount />
	<OnDestroyIntervals />
	<BeforeAndAfterUpdate />
	<Tick />
	<h1>The count is {countValue}</h1>
	<Incrementer/>
	<Decrementer/>
	<Resetter/>
	<h1>The count is {$countAutoSubscriptions}</h1>
	<IncrementerAutoSubscriptions/>
	<DecrementerAutoSubscriptions/>
	<ResetterAutoSubscriptions/>
	<h1>The time is {formatter.format($time)}</h1>
	<h1>The time is {formatter.format($time)}</h1>
	<p>
		This page has been open for
		{$elapsed} {$elapsed === 1 ? 'second' : 'seconds'}
	</p>
	<h1>The count is {$countCustom}</h1>
	<button on:click={countCustom.increment}>+</button>
	<button on:click={countCustom.decrement}>-</button>
	<button on:click={countCustom.reset}>reset</button>

</main>

dan hasilnya akan seperti ini…

Okay sudah berhasil ya… berikut link github ada disini… cyaaaa….

Bima Sena

Leave a Reply

Your email address will not be published. Required fields are marked *