references/mutations.md · 24000
guide](reactivity.md#changing-query-parameters), give Channel a userId prop and pass it to Messages with channelId. Read userId from the Managed Better Auth session where you render Channel, as frontend/main.tsx does in render the app:
// ...imports and useSealedQuery() as in the reactivity guide
export function Channel({ channelId, userId }: { channelId: number; userId: string }) {
const sealed = useSealedQuery(channelId)
// Renewals must be for the same query, so refresh with the same channel
const refreshQuery = useCallback(() => fetchSealedMessages(channelId), [channelId])
if (sealed?.sealedQuery) {
return (
<Messages
sealedQuery={sealed.sealedQuery}
refreshQuery={refreshQuery}
channelId={channelId}
userId={userId}
/>
)
}
if (sealed?.error) {
return <p role="alert">Couldn't open this channel</p>
}
return <p>Loading messages</p>
}
With TanStack DB collections
For more control, keep optimistic state in a TanStack DB collection. Every query and component that reads the collection then sees the same optimistic changes, and they stay consistent across client-side joins. Failed writes roll back automatically, and one transaction can span several collections.
Add mutation handlers to createMessagesCollection() in frontend/collections.ts, from the reactivity guide. TanStack DB calls each handler once per transaction, with all of its mutations, so each handler sends them to your backend in one request. If the write committed, the handler waits for its txid before it returns, so TanStack DB keeps the optimistic state until the change has synced:
import { createCollection } from "@tanstack/react-db"
import { realtimeCollectionOptions } from "@neon/realtime-tanstack"
import type { SealedLiveQuery } from "@neon/realtime/client"
import type { Message } from "../backend/schema"
import { deleteMessages, editMessages, fetchSealedInbox, sendMessages } from "./api"
import { client } from "./client"
export function createMessagesCollection(sealedQuery: SealedLiveQuery<Message>) {
return createCollection(
realtimeCollectionOptions({
id: "messages",
client,
query: sealedQuery,
refreshQuery: fetchSealedInbox,
getKey: (message) => message.id,
onInsert: async ({ transaction, collection }) => {
const result = await sendMessages(transaction.mutations.map(({ modified }) => modified))
if (result.kind === "committed") {
await collection.utils.awaitTxId(result.txid, 10_000)
}
},
onUpdate: async ({ transaction, collection }) => {
const result = await editMessages(transaction.mutations.map(({ modified: { id, body } }) => ({ id, body })))
if (result.kind === "committed") {
await collection.utils.awaitTxId(result.txid, 10_000)
}
},
onDelete: async ({ transaction, collection }) => {
const result = await deleteMessages(transaction.mutations.map(({ original }) => original.id))
if (result.kind === "committed") {
await collection.utils.awaitTxId(result.txid, 10_000)
}
}
})
)
}
export type MessagesCollection = ReturnType<typeof createMessagesCollection>
While a handler runs, TanStack DB holds back synced changes. When the handler returns, it drops the optimistic state and applies the synced rows together, so a sent message's optimistic row gives way to its synced row, which has the same id, in a single step. If a handler throws, the optimistic change rolls back. collection.utils.awaitTxId() resolves once the transaction has entered TanStack DB's sync queue, and it takes the same explicit timeout.
Then write through the collection. This is the optimistic version of frontend/Inbox.tsx from the reactivity guide. It runs the same local query, and its insert(), update() and delete() calls apply each change locally at once and call the matching handler:
import type { FormEvent } from "react"
import { eq, useLiveQuery as useCollectionQuery } from "@tanstack/react-db"
import type { Message } from "../backend/schema"
import type { MessagesCollection } from "./collections"
import { newMessage } from "./mutations"
interface Props {
messagesCollection: MessagesCollection;
channelId: number;
userId: string;
}
export function Inbox({ messagesCollection, channelId, userId }: Props) {
const { data, isReady, isError } = useCollectionQuery({
query: (q) =>
q
.from({ message: messagesCollection })
.where(({ message }) => eq(message.channel_id, channelId))
.orderBy(({ message }) => message.created_at, "desc")
})
function send(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
const form = event.currentTarget
const body = String(new FormData(form).get("body") ?? "").trim()
if (body) {
form.reset()
messagesCollection.insert(newMessage(channelId, userId, body))
}
}
function edit(message: Message) {
const body = window.prompt("Edit message", message.body)?.trim()
if (body) {
messagesCollection.update(message.id, (draft) => {
draft.body = body
})
}
}
if (isError) {
return <p role="alert">Couldn't sync messages</p>
}
if (!isReady) {
return <p>Loading messages</p>
}
return (
<section>
<form onSubmit={send}>
<input name="body" placeholder="Message" required />
<button type="submit">Send</button>
</form>
<ul>
{data.map((message) => (
<li key={message.id} aria-busy={message.$hasPendingWrites}>
{message.body}
{message.author_id === userId && (
<>
<button disabled={message.$hasPendingWrites} onClick={() => edit(message)} type="button">
Edit
</button>
<button
disabled={message.$hasPendingWrites}
onClick={() => messagesCollection.delete(message.id)}
type="button"
>
Delete
</button>
</>
)}
</li>
))}
</ul>
</section>
)
}
$hasPendingWrites is true while a row has a pending optimistic change, which disables its buttons, so you don't start a new change on a message whose last change isn't confirmed yet. Edit and Delete show only on the user's own messages, and the routes still enforce authorship. Each call returns a TanStack DB transaction, and its when("settled") promise rejects with the handler's error if the write fails and the change rolls back, so you can await it to show an error.
An optimistic insert needs a whole Message, so the component also takes the signed-in user's id. It only fills in the optimistic row, because the server takes the author from the verified token. Read it from the Managed Better Auth session where the app creates the collection, as frontend/main.tsx does in render the app.
The TanStack example puts these handlers into a full app with server-side rendering, and the Next.js example shows the React binding in a server-rendered app.
Render the app
frontend/main.tsx from the reactivity guide renders both views inside RealtimeProvider. Read the signed-in user's id from the session and pass it to Channel and Inbox:
import { StrictMode } from "react"
import { createRoot } from "react-dom/client"
import { RealtimeProvider } from "@neon/realtime-react"
import { fetchSealedInbox } from "./api"
import { authClient } from "./auth"
import { Channel } from "./Channel"
import { client } from "./client"
import { createMessagesCollection } from "./collections"
import { Inbox } from "./Inbox"
const root = createRoot(document.getElementById("root")!)
const { data: session } = await authClient.getSession()
if (!session) {
root.render(<p>Sign in to see the messages.</p>)
} else {
const userId = session.user.id
const messagesCollection = createMessagesCollection(await fetchSealedInbox())
root.render(
<StrictMode>
<RealtimeProvider client={client}>
<Channel channelId={2} userId={userId} />
<Inbox messagesCollection={messagesCollection} channelId={2} userId={userId} />
</RealtimeProvider>
</StrictMode>
)
}
Signed out, it renders a message instead of the views. Sign-in isn't part of these guides: the running example shows one way to add it.