← Back to patterns

Single-flight mutations

Mutate and refresh in one request, with optimistic updates

Pattern Usage:

// todos.remote.ts
export const addTodo = form(schema, async ({ text }) => {
  save([...load(), newTodo(text)]);
  void getTodos().refresh();        // server-driven
});

export const toggleTodo = command(z.string(), async (id) => {
  save(toggle(load(), id));
  await requested(getTodos, 1).refreshAll(); // accept client request
});

// +page.svelte
const todos = getTodos();

await toggleTodo(id).updates(
  todos.withOverride((list) => list.map(...)) // optimistic
);

Live Demo:

Loading…

Requests

Commands in flight: 0

How it works: Normally a mutation is followed by a second request that refetches the data. With single-flight mutations the fresh query data travels back in the same response.

Server-driven (add): the form handler calls getTodos().refresh() or .set(value). Client-requested (toggle, delete): the client passes .updates(query) and the server opts in with requested(getTodos, limit); the limit is mandatory so clients can't make the server refresh arbitrary queries.

withOverride() shows the expected result immediately and is dropped when the response arrives, or rolled back if the request fails. Each command takes 800 ms so you can see it. Your todos live in a cookie, so they are private to you.