Repository navigation
Description
I have a component that is using a live query and then aims to perform update or delete operations on the results:
import React from 'react'
import { useLiveQuery, useOptimisticMutation } from '@tanstack/react-db'
import { mutationFn, taskCollection } from '../db'
function TaskList() {
const { data: tasks } = useLiveQuery((query) => (
query
.from({ taskCollection })
.select('@id', '@title', '@status', '@inserted_at')
.orderBy({'@inserted_at': 'desc'})
.keyBy('@id')
))
const deleteTask = useOptimisticMutation({ mutationFn })
const handleDelete = (task) => {
deleteTask.mutate(() => {
taskCollection.delete(task)
})
}
return (
<ul className="mx-2 my-6">
{tasks.map((task) => (
<li key={`task-${task.id}`} className="bg-zinc-200 rounded-lg m-4 p-6">
<button className="float-right" onClick={() => handleDelete(task) }>
✕
</button>
{task.title}
</li>
))}
</ul>
)
}
export default TaskListPerforming the delete fails with Error: Object not found in collection. This is because the delete code in https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L772 tries to lookup the object key from collection.objectKeyMap and the lookup fails.
The same behaviour occurs for updates.
Now... in my tasks data from the query result, I get the ID but I don't get the key. I can get a delete mutation to be emitted by passing in the id:
const handleDelete = (task) => {
deleteTask.mutate(() => {
taskCollection.delete(task.id)
})
}However, this doesn't help: (a) it doesn't delete locally and (b) it doesn't lookup the syncMetadata correctly because this looks it up by key, not ID, so the backend doesn't know what to apply the mutation to.
If I construct the correct key manually, then delete works, e.g.:
const handleDelete = (task) => {
deleteTask.mutate(() => {
key = `"public"."tasks"/"${task.id}"`
taskCollection.delete(key)
})
}However, update doesn't because update requires an object.
I assume that the problem is just the way we're using a weakHashMap to lookup key from object and that the object returned from the query result is not the object that's in the key of the map.
Activity
KyleAMathews commentedon May 23, 2025
Yes this is the fix #54
You can see that workaround in the example app which is to find the object from the original collection.
samwillis commentedon May 23, 2025
I the best solution to this is to add the
getId: (item) => item.idconfig option to all collections that's proposed in #79. Although I would advocate for calling itgetKeyorkeyBy, that latter is an option in the query builder and has the same effect.This lets the user decide on a collect-by-collection basis what their key is, this can then easily be accessible all the way through the query pipeline (with any joins, aggregates) without having to add any magic.