Helper function to create a derived rune in svelte 5 which can be mutated
<script>
import { derivedMutable } from '@vanillacode314/svelte-derived-mutable';
async function createTodo(title) {
await new Promise((resolve) => setTimeout(resolve, 1000));
// NOTE: appending on server to demonstrate the derivation behaviour
todos.push(title + ' on server');
}
let todos = $state(['a', 'b', 'c']);
// NOTE: use $state.snapshot to deepTrack the value
const optimisticTodos = derivedMutable(() => $state.snapshot(todos));
async function addTodo(title) {
optimisticTodos.value.push(title);
await createTodo(title);
}
</script>
<ul>
{#each optimisticTodos.value as todo}
<li>{todo}</li>
{/each}
</ul>
<button onclick={() => addTodo('test')}>Add Todo</button>
$state.snapshot
like the usage example..value
property regardless of whether the value is primitive or object.Run this command where you want to download the file
curl "https://raw.githubusercontent.com/vanillacode314/svelte-derived-mutable/refs/heads/main/src/lib/index.svelte.ts" -o svelte-derived-mutable.svelte.ts
npm install @vanillacode314/svelte-derived-mutable
yarn add @vanillacode314/svelte-derived-mutable
pnpm add @vanillacode314/svelte-derived-mutable
bun add @vanillacode314/svelte-derived-mutable