Skip to content

Default task

This is the way to create a default task.

There’s no concurrency management in this task and every perform will be executed immediately.

Usage

To specify a default task, you can either use the dot notation or the options notation.

<script lang="ts">
import { task } from '@sheepdog/svelte';
const myTask = task(async () => {
// your code
});
</script>

The task store

The return value of the task function will be a svelte store where you can access state from all the instances running and eventually cancel them with cancelAll.

Passing props

While defining a task, if the function that you pass in has some arguments, those will be required by the perform function (and it will be strongly typed too).

<script lang="ts">
import { task } from '@sheepdog/svelte';
const myTask = task(async (id: string) => {
// your code
});
</script>
<button
on:click={() => {
myTask.perform('42');
}}>perform</button
>

Getting the return value

If you return something from your task you can access the return value by awaiting the perform function.

<script lang="ts">
import { task } from '@sheepdog/svelte';
const myTask = task(async () => {
return 42;
});
</script>
<button
on:click={() => {
const number = await myTask.perform();
console.log(number); // 42
}}>perform</button
>

Getting the TaskInstance

If you don’t await the perform function, then you’ll get back the task instance that you can use either to cancel it or to get its current state. The TaskInstance is also a svelte store and you can access the current value with instance.get().

<script lang="ts">
import { task } from '@sheepdog/svelte';
const myTask = task(async () => {
// your code
});
</script>
<button
on:click={() => {
const lastRun = myTask.perform();
console.log(lastRun.get()); // { isRunning: true, hasStarted: true, ... }
lastRun.cancel();
}}>perform</button
>