Writes FULL v1.5+
A query declares where its data comes from with from, and where changes go with to.
This page covers declaring that destination and calling write() and create(), including how the query reads the server's answer.
Optimistic Updates and Rollback covers what appears on screen while the request is still out.
Declaring the Destination v1.5+
The shortest way to declare a write side is a URL. to is the row's address, and the query derives the two operations every row has:
wildflower.query('items', {
from: '/api/items',
key: 'id',
deleted: 'removed',
to: '/api/items/:id', // update at PATCH, delete at DELETE
body: item => item // what to send
});
wildflower.getQuery('items').write({ id: 42, done: true }); // PATCH /api/items/42
wildflower.getQuery('items').write({ id: 42, removed: true }); // DELETE /api/items/42
The URL is used exactly as written. Nothing is invented from it, and only the verb differs between the two. The verb is PATCH rather than PUT, because write() is a partial field merge and PUT would tell the server to replace the whole record.
Declare body or nothing is sent. An operation carries no request body unless one is declared, because operations differ in payload inside a single query and guessing a shape for one would send the wrong thing for another. body: item => item sends the item; body: item => ({ article: item }) wraps it for an envelope API. Development builds warn (WF-977) when an update or create is about to go out empty while the item has fields to send, since that request succeeds and changes nothing.
Named operations
Plenty of writes are not an update or a delete. A favorite toggle is two verbs on one sub-resource URL, and neither is derivable from the row. Give them names:
wildflower.query('feed', {
from: '/api/articles',
key: 'slug',
to: {
favorite: { url: '/api/articles/:slug/favorite', method: 'POST',
confirmation: d => d.article },
unfavorite: { url: '/api/articles/:slug/favorite', method: 'DELETE',
confirmation: d => d.article }
}
});
wildflower.getQuery('feed').write('favorite', { slug: 'how-to-train', favorited: true });
A map declares exactly the operations it lists. Asking for one it does not have raises an error identifying the missing operation (WF-974) rather than quietly falling back to update, and nothing is sent. update and delete keep their meaning inside a map: an entry named delete is the lifecycle delete and applies your declared deleted field itself, so one entry cannot behave one way when derived and another when called by name.
Include the fields the operation changes, not just the key. A write carrying only the key claims nothing, so a rejection has nothing to roll back, and development builds warn with WF-976.
Creating rows
create is its own option rather than an entry in the map, because it is the one operation that creates a row rather than addressing an existing one. Its URL is the collection, and the query generates the temporary key for you:
wildflower.query('comments', {
from: '/api/articles/:slug/comments',
key: 'id',
deleted: 'removed',
params: () => ({ slug: wildflower.getStore('route').slug }),
select: d => d.comments,
to: { delete: { url: '/api/articles/:slug/comments/:id', method: 'DELETE' } },
create: {
url: '/api/articles/:slug/comments',
method: 'POST',
body: item => ({ comment: { body: item.body } }),
confirmation: d => d.comment
}
});
wildflower.getQuery('comments').create({ body: 'Nice write-up' });
The row appears immediately under a tmp- key, the server's record replaces it under the real key with no duplicate and no flicker, and a rejection removes the row that only ever existed optimistically. The generated key is never sent, since it is only local bookkeeping, so body: item => item will not post an id the server never issued. Pass your own key and it is used as given and sent like any other field, which is how a client-generated id against a PUT endpoint works.
Within that one query, the delete sends no body while the create sends an envelope, and :id comes from the item while :slug comes from params, both in the same URL. That is why body and confirmation are per-operation. The query-level ones apply to update and create; anything else declares its own. Declared params reach a write URL only through its :tokens. The query string they add to read requests is never appended to a write.
What comes back
confirmation extracts the server's answer for the row, and declaring it is what decides between reconciling and refetching. Declare it, and the response is parsed and applied as the row's new value. Leave it off, and an ok response means only that the request succeeded, so the query refetches to find out what was saved.
An ok response can mean three different things, and only the body can say which, so confirmation decides all three. It receives the parsed body and the item that was written:
confirmation: (body, item) => {
if (!body.success) throw new Error(body.error); // refused: reject and roll back
if (body.row) return body.row; // here is the row: reconcile it
return item; // accepted, nothing to apply
}
Returning the item says the row is what you sent, so the optimistic value stands and no refetch follows. That is the answer for an endpoint that replies { success: true } and nothing more. It is a claim you are making about that endpoint, and it is wrong wherever the server transforms what it stores, by trimming a string, stamping a timestamp, clamping a number, or recomputing a total from the field you changed. On a create it is also wrong for the key, since the item carries the generated tmp- key and the row keeps it until the next fetch. Where any of that is true, return nothing and let the query fetch the truth.
A status code cannot make this decision on its own, which is why it is not a declared option. Plenty of APIs answer 200 with { success: false }, and telling that apart from a real success needs the body.
A successful response with no body at all is not an error. 204 No Content is the ordinary answer to a delete, and an empty body simply means there was nothing to apply, so the query refetches. The confirmation is not called in that case.
Writes
A query declares how data comes in with from. It declares how data goes out with to. Where the declarative form above cannot express a transport, to also takes a function that does the network call itself, and the query handles everything around it either way: showing the change immediately, tracking whether it's confirmed yet, and undoing it if the server says no. The function form is supported permanently, and a query can use it for reads while declaring its writes, or the reverse.
wildflower.query('orders', {
from: '/api/orders',
key: 'id',
to: item => fetch('/api/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(item)
})
});
wildflower.component('order-form', {
state: { draft: '' },
addItem() {
wildflower.getQuery('orders').write({ id: 'tmp-' + Date.now(), name: this.draft });
}
});
Calling write(item) applies the item to the rows right away, so nobody waits on the round trip to see their own change, and the request goes out behind it.
A keyed item merges into the row it names, and a key that matches nothing yet appends a new row, which is how the example above adds an order before the server has seen it.
Optimistic Updates and Rollback covers that window in full, including what a rejection undoes.
A write to a list has to identify its row. An item with no key identifies none, so the write is rejected rather than guessing at one (WF-969). This depends on the query's shape and not on whether you spelled out key:, since key defaults to id: a query rendering a list is keyed either way. A record-shaped query is the other side of the same rule. It holds one record, so there is no row to identify and an unkeyed payload merges straight into it, and for the same reason create() on a record query is an error rather than a second record (WF-982). If one query supplies both a list and a record view, it counts as a list, because a list binding means its rows carry keys.
Telling the query what happened
Once your to function's promise settles, the query looks at what it resolved (or rejected) with to decide what happens next. There are three outcomes, and which one you get depends only on what you return.
Resolve with the saved record, and the query replaces the optimistic row with the real one, no second request needed. Parse the JSON body and hand it back:
to: item => fetch('/api/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(item)
}).then(r => r.json()) // resolves with the record the server saved
This is the fast path. If the server assigned a real id, the temporary one you made up (tmp-1755...) gets swapped out for it automatically, and every other field on the row updates to match whatever the server actually stored.
Resolve with nothing, or leave off .then(r => r.json()) entirely, and the query invalidates and re-fetches to find out what really happened:
to: item => fetch('/api/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(item)
}) // no .then() here: resolves with a raw Response, which the
// query can't use as a record, so it triggers a refresh instead
A raw, un-parsed fetch() response counts as "nothing" as long as it's ok. The query can see that the request succeeded, but there is no record in it to apply directly, so it refetches instead. This is the simplest way to wire up to: skip the .then() and let the query do one extra read to stay correct.
The same "nothing" path also covers a resolved value that doesn't carry the query's key. If your API answers a save with a status envelope like { success: true } rather than the saved record, a keyed query has no id to match against, so it cannot use that as the row and falls back to refetching. Development builds warn about this (WF-965). If your API's response really does have the data you want applied directly, make sure the key is on it: return { ...body, id: item.id } when the response is missing the id you already know.
A resolved record follows JSON Merge Patch (RFC 7396). A field present with a value applies, overwriting the row's current value. A field present as null removes it from the row. A field the response simply doesn't mention is left exactly as it was. An endpoint can safely echo back only what it actually touched. A PATCH that confirms with { id, stock: 73 } updates stock and leaves every other field on the row untouched, no extra work required on your end:
to: changes => fetch('/api/orders/' + changes.id, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(changes)
}).then(r => r.json()) // { id: 42, stock: 73 }; other fields on the row are untouched
To clear a field, resolve with it set to null explicitly, since an omitted field leaves the row's current value alone.
Reject, and the optimistic change rolls back. A raw fetch() response that comes back not-ok (a 4xx or 5xx status) is treated as a rejection automatically, in the shape HTTP <status>, the same error shape a failed read uses, so you do not have to check r.ok and throw yourself:
to: item => fetch('/api/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(item)
})
// a 400 or 500 response here rejects on its own as "HTTP 400" / "HTTP 500"
Two decisions produce those three outcomes: whether you parse the response (fast path or refetch), and whether the server accepted the write at all (success or rollback). Returning the parsed record saves a round trip when your API supports it; returning nothing is simpler to write and just as correct, since the query fetches its own confirmation either way.
Returning nothing has one cost worth knowing about if you run read replicas or a cache in front of your API: the refetch can answer from a machine that has not caught up with the save yet. Declaring a confirmation avoids the round trip entirely, so the problem does not arise. The refetch race covers what the query can and cannot tell apart there.
When the server says no
write() returns a promise that rejects on failure, so an ordinary try/catch around it works as you'd expect.
The failure shows up in syncError rather than error, which is reserved for a failed first load, and the rows stay on screen either way, so nothing goes blank.
The optimistic change is undone field by field, and only for the fields that write still owns, so two writes in flight on one row fail independently. Optimistic Updates and Rollback covers the claim rules and what a rejected create or delete does.
Deletes
Deletes need one extra declaration on the query: the name of a field that marks a row as deleted. Once that is in place, a delete is a write like any other. A row carrying a truthy value in that field is removed from the list instead of merged into it, and your to function sees that same field, so one function can route creates, updates, and deletes at once:
wildflower.query('orders', {
from: '/api/orders',
key: 'id',
deleted: 'deleted',
to: item => item.deleted
? fetch('/api/orders/' + item.id, { method: 'DELETE' })
: fetch('/api/orders', { method: 'POST', body: JSON.stringify(item) })
});
// The row leaves the screen now; the DELETE request catches up behind it.
wildflower.getQuery('orders').write({ id: 42, deleted: true });
Without a deleted declaration on the query, a truthy value in that field merges in as ordinary row data and nothing is removed. Calling write() on a query that never declared to rejects (WF-964), since there would be nowhere for the write to go. Every write() and create() failure rejects the returned promise, so one .catch sees them all.
The same applies when you call the delete by name. write('delete', { id: 42 }) against a to map sends the request whether or not deleted is declared, but only a declared tombstone field removes the row on screen. Without one the request succeeds, the server drops the record, and the row sits there until the next sync fetches a list that no longer contains it, which reads as a delete button that does nothing for a second or two. Development builds warn when it happens (WF-975). Declare deleted alongside the map and the named delete removes the row immediately, exactly as the derived one does.
Here is everything above in one place, against a simulated server with real latency. Tick a task and the change appears before the save settles. Flip the switch and try again: the server refuses, and exactly the written field rolls back. Delete with the switch on, and the row comes back.
<div data-component="write-demo">
<div class="form-check form-switch mb-2">
<input class="form-check-input" type="checkbox" id="wd-arm"
data-action="change:setArm">
<label class="form-check-label" for="wd-arm">server rejects saves</label>
</div>
<ul class="list-group" data-query="writes-demo">
<template>
<li class="list-group-item d-flex align-items-center gap-2">
<button class="btn btn-sm btn-outline-secondary" data-action="toggleDone"
data-bind="mark"></button>
<span data-bind="title" data-bind-class="rowClass"></span>
<button class="btn btn-sm btn-outline-danger ms-auto"
data-action="remove">delete</button>
</li>
</template>
</ul>
<p class="small text-muted mt-2 mb-0" data-bind="status"></p>
</div>
// The demo server: three rows in memory behind ~900ms of latency, and
// a switch that makes it refuse saves. One `to` routes updates and
// deletes alike — no fetch mocking, just a function source.
let rows = [
{ id: 1, title: 'Water the seed trays', done: true },
{ id: 2, title: 'Label the new beds', done: false },
{ id: 3, title: 'Fix the drip line', done: false }
];
let rejectSaves = false;
const wait = ms => new Promise(r => setTimeout(r, ms));
wildflower.query('writes-demo', {
from: () => rows.map(r => ({ ...r })),
key: 'id',
deleted: 'removed',
to: async item => {
await wait(900);
if (rejectSaves) throw new Error('HTTP 409');
if (item.removed) {
rows = rows.filter(r => r.id !== item.id);
return; // nothing: the query refetches
}
rows = rows.map(r => r.id === item.id ? { ...r, ...item } : r);
return rows.find(r => r.id === item.id); // the saved record
}
});
wildflower.component('write-demo', {
state: { status: 'Every change lands on screen first; the save follows.' },
computed: {
// Item-level computeds: fn(item) evaluates per row.
mark(item) { return item.done ? '☑' : '☐'; },
rowClass(item) {
return item.done ? 'text-decoration-line-through text-muted' : '';
}
},
setArm(event) { rejectSaves = event.target.checked; },
toggleDone(event, element, details) {
const t = details.item;
this.report(
wildflower.getQuery('writes-demo').write({ id: t.id, done: !t.done }),
(t.done ? 'reopen' : 'complete') + ' “' + t.title + '”'
);
},
remove(event, element, details) {
this.report(
wildflower.getQuery('writes-demo').write({ id: details.item.id, removed: true }),
'delete “' + details.item.title + '”'
);
},
// write() returns a promise: confirmation and rollback are both
// observable, so the demo narrates them.
report(saving, label) {
this.status = 'Saving — ' + label + '…';
saving.then(
() => { this.status = 'Confirmed — ' + label; },
() => { this.status = 'Rejected — ' + label + ' — rolled back.'; }
);
}
});
The transport is an in-memory function, and the write path does not depend on that. Swap the function body for a fetch() and the behavior on screen is identical. The query handles the optimistic apply and the rollback, and your to makes one request.
One entity in two queries
Queries are independent stores, each with its own copy of whatever rows it holds. So when the same server entity shows up in two different queries, say an order detail view and an order list, each query keeps its own copy with its own claims, and a write through one leaves the other's copy alone until that second query happens to refresh on its own schedule. The alternative would be a normalized cache, which why two queries do not share a row works through.
The cost is lag. Save through a detail query, and a list query showing the same row keeps its old values until its next refresh. When two views need to agree immediately, invalidate the sibling once the write has settled:
await wildflower.getQuery('order-detail').write({ id: 42, status: 'shipped' });
wildflower.getQuery('orders').invalidate(); // the list catches up now
// several siblings at once
await wildflower.invalidateQueries('orders', 'dashboard-counts');
wildflower.invalidateQueries() takes any number of query names, invalidates each, and returns a promise that resolves once every triggered refetch has settled, so a write flow can await the whole convergence. Queries nothing is currently observing are skipped rather than activated; an inactive query always revalidates when its next observer arrives, so there is nothing to catch up. A name that matches no registered query warns in dev builds (WF-955) and the rest still run.
What this asks of you as the app grows
Keeping that list of names current is your job, and it is the cost of queries that do not share a cache. Six months from now you add a third view of the same entity, an order summary card beside the list and the detail. Every write that touches an order now needs the new query's name added to it. If you miss one, that view shows old values until its own next refresh, and nothing tells you. There is no error, warning, or failed request to find in the network tab, because from the framework's side nothing went wrong.
How much this costs depends on how many views of the same records are on screen at the same time, which is usually a small number. Applications organized around pages or routes rarely feel it at all, since a detail page and a list page are seldom open together, and a query nothing is showing revalidates by itself when something finally shows it. The case that needs attention is a dense dashboard, where several panels over the same records are visible at once because that is what a dashboard is for.
Put the invalidateQueries call directly after the write it follows rather than burying it in a helper, so the list of names is visible at the one place you would ever need to update it. When you are unsure whether a query belongs in that list, include it. An unnecessary invalidation costs one conditional request that usually comes back 304 Not Modified with no body, while a missing one is the silent staleness above.
Where to Next
Optimistic Updates and Rollback covers what a write puts on screen before the server answers: the claim rules that decide what a failure undoes, the pendingWrites count for saving indicators, what a page unload costs an unsent write, and patch() for adding the same optimism by hand when the query cannot own the transport.
Boundaries and Guarantees collects the rules a query follows at its boundaries: the races it will not guess at, the limits of the credential scope, and why writes never retry.
Declarative writes against a server with an added delay. A server-computed work estimate comes from an async computed, and persisted rows paint instantly on reload.