T
TanStack3w ago
sensitive-blue

Using awaitTxId() after a backend transaction that updates multiple collections

If I have a backend transaction that updates multiple tables (so multiple collections are affected), and I get its txid, would doing this on the client work as expected?
await collection1.utils.awaitTxId(txid)
await collection2.utils.awaitTxId(txid)
await collection1.utils.awaitTxId(txid)
await collection2.utils.awaitTxId(txid)
My idea is to use createOptimisticAction like this:
const data = createOptimisticAction<string>({
onMutate: (data) => {
collection1.update(data.collection1.id, (draft) => {
draft.foo = data.collection1.foo
})

collection2.update(data.collection2.id, (draft) => {
draft.bar = data.collection2.bar
})
},
mutationFn: async (data) => {
const { txid } = await api.update(data)
await collection1.utils.awaitTxId(txid)
await collection2.utils.awaitTxId(txid)
},
})
const data = createOptimisticAction<string>({
onMutate: (data) => {
collection1.update(data.collection1.id, (draft) => {
draft.foo = data.collection1.foo
})

collection2.update(data.collection2.id, (draft) => {
draft.bar = data.collection2.bar
})
},
mutationFn: async (data) => {
const { txid } = await api.update(data)
await collection1.utils.awaitTxId(txid)
await collection2.utils.awaitTxId(txid)
},
})
Does this make sense, and would it work as expected? I want to have an optimistic action without changing my backend logic, for cases where the backend transaction updates multiple collections.
2 Replies
metropolitan-bronze
metropolitan-bronze3w ago
Yup! That's the exact pattern we recommend
metropolitan-bronze
metropolitan-bronze3w ago
Mutations | TanStack DB Docs
TanStack DB Mutations TanStack DB provides a powerful mutation system that enables optimistic updates with automatic state management. This system is built around a pattern of optimistic mutation → ba...

Did you find this page helpful?