T
TanStack2mo ago
absent-sapphire

how can i insert with a temporary id and avoiding colide

14 Replies
deep-jade
deep-jade2mo ago
randomness e.g. Math.random or crypto.randomUUID
absent-sapphire
absent-sapphireOP2mo ago
export const addToCollection = createOptimisticAction<{
productId: number
rating?: number
userId: number
}>({
onMutate: ({ productId, rating, userId }) => {
triedsCollection.insert({
id: Math.floor(Math.random() * (-10000 - -1 + 1) + -1),
userId,
createdAt: new Date(),
note: rating,
productId,
})
},
mutationFn: async ({ productId, rating }, { transaction }) => {
let tried = await addToCollectionApi({ productId, rating })

triedsCollection.utils.writeInsert(tried)
}
})
export const addToCollection = createOptimisticAction<{
productId: number
rating?: number
userId: number
}>({
onMutate: ({ productId, rating, userId }) => {
triedsCollection.insert({
id: Math.floor(Math.random() * (-10000 - -1 + 1) + -1),
userId,
createdAt: new Date(),
note: rating,
productId,
})
},
mutationFn: async ({ productId, rating }, { transaction }) => {
let tried = await addToCollectionApi({ productId, rating })

triedsCollection.utils.writeInsert(tried)
}
})
how can i do that tried got rolledback
const tx = triedsCollection.update(oldTriedId, (draft) => {
draft.id = tried.id
})
const tx = triedsCollection.update(oldTriedId, (draft) => {
draft.id = tried.id
})
doing that doesnt work either i want to modify the id
deep-jade
deep-jade2mo ago
what collection type are you using?
absent-sapphire
absent-sapphireOP2mo ago
live querycollection sorry
deep-jade
deep-jade2mo ago
if you're going to do a direct write, you also need to return { refetch: false } as by default it refetches your collection
absent-sapphire
absent-sapphireOP2mo ago
i do return a refresh: false
export const triedsCollection = createCollection(
queryCollectionOptions({
queryClient: queryClient,
queryKey: ['trieds'],
queryFn: async ({ signal }) => {
return await getCollection("trieds", { signal })
},
getKey: (item) => item.id,
onInsert: async () => {
return { refetch: false }
},
onUpdate: async () => {
return { refetch: false }
},
onDelete: async () => {
return { refetch: false }
}
})
)
export const triedsCollection = createCollection(
queryCollectionOptions({
queryClient: queryClient,
queryKey: ['trieds'],
queryFn: async ({ signal }) => {
return await getCollection("trieds", { signal })
},
getKey: (item) => item.id,
onInsert: async () => {
return { refetch: false }
},
onUpdate: async () => {
return { refetch: false }
},
onDelete: async () => {
return { refetch: false }
}
})
)
return in the mutationFn ? it doesnt work either
deep-jade
deep-jade2mo ago
oh sorry, yeah in a action it doesn't refetch automatically why aren't you using onInsert and just letting it refresh?
absent-sapphire
absent-sapphireOP2mo ago
too slow with a bad network from the transaction object i cant modify the id ? ok the insert work just query doesnt refresh @Kyle Mathews the query doesnt refresh on the writeinsert return an undefined
const { data: [data] } = useLiveQuery((q) => {
const triedByUser = q.from({ tried: triedsCollection })
.where(({ tried }) => eq(tried.userId, user?.id))

return q.from({ product: productsCollection })
.leftJoin({ tried: triedByUser }, ({ tried, product }) =>
eq(tried.productId, product.id)
)
.leftJoin({ brand: brandsByProduct }, ({ brand, product }) =>
eq(brand.id, product.id)
)
.where(({ product }) => eq(product.upcId, barcode))
.select(({ product, tried, brand }) => ({
product,
tried,
brands: brand.brands
}))
}, [barcode, user])
const { data: [data] } = useLiveQuery((q) => {
const triedByUser = q.from({ tried: triedsCollection })
.where(({ tried }) => eq(tried.userId, user?.id))

return q.from({ product: productsCollection })
.leftJoin({ tried: triedByUser }, ({ tried, product }) =>
eq(tried.productId, product.id)
)
.leftJoin({ brand: brandsByProduct }, ({ brand, product }) =>
eq(brand.id, product.id)
)
.where(({ product }) => eq(product.upcId, barcode))
.select(({ product, tried, brand }) => ({
product,
tried,
brands: brand.brands
}))
}, [barcode, user])
// product from productsCollection
{"id": 8, "name": "Eau minérale naturelle", "upcId": "3068320120256"}
// tried from triedsCollection
{"createdAt": "2025-08-26T22:24:06.628Z", "id": 286, "note": null, "productId": 8, "userId": 1}
// product from productsCollection
{"id": 8, "name": "Eau minérale naturelle", "upcId": "3068320120256"}
// tried from triedsCollection
{"createdAt": "2025-08-26T22:24:06.628Z", "id": 286, "note": null, "productId": 8, "userId": 1}
the query is returning undefined on tried even when i refresh the app the query doesnt retrieve the tried object, even though it is in the collection
deep-jade
deep-jade2mo ago
are you on the latest release of tanstack db?
absent-sapphire
absent-sapphireOP2mo ago
yes
deep-jade
deep-jade2mo ago
perhaps it's just your query that's wrong then
absent-sapphire
absent-sapphireOP2mo ago
idk how can it be wrong sometimes it work sometimes not i dont understand the productId is 8 and theres a tried item with a productId of 8 the userId is 1 and 1 on the tried object if i remove the where statement it doesnt work either the product is never undefined brands neither
deep-jade
deep-jade2mo ago
perhpas just have a debug query which is querying the whole collection and then logging that to the console?
absent-sapphire
absent-sapphireOP2mo ago
Map {291 => {"createdAt": "2025-08-26T23:30:37.345Z", "id": 291, "note": 3.5, "productId": 8, "userId": 1}, 232 => {"createdAt": "2025-08-12T14:08:48.308Z", "id": 232, "note": 2.5, "productId": 14, "userId": 1}, 197 => {"createdAt": "2025-08-07T19:33:51.298Z", "id": 197, "note": 2.5, "productId": 13, "userId": 1}}
Map {291 => {"createdAt": "2025-08-26T23:30:37.345Z", "id": 291, "note": 3.5, "productId": 8, "userId": 1}, 232 => {"createdAt": "2025-08-12T14:08:48.308Z", "id": 232, "note": 2.5, "productId": 14, "userId": 1}, 197 => {"createdAt": "2025-08-07T19:33:51.298Z", "id": 197, "note": 2.5, "productId": 13, "userId": 1}}
trieds collection
Map {8 => {"id": 8, "name": "Eau minérale naturelle", "upcId": "3068320120256"}, 13 => {"id": 13, "name": "Monster energy ultra gold", "upcId": "5060947541924"}, 14 => {"id": 14, "name": "Coca-Cola 33cl", "upcId": "5449000000996"}}
Map {8 => {"id": 8, "name": "Eau minérale naturelle", "upcId": "3068320120256"}, 13 => {"id": 13, "name": "Monster energy ultra gold", "upcId": "5060947541924"}, 14 => {"id": 14, "name": "Coca-Cola 33cl", "upcId": "5449000000996"}}
products collection when i put the same id in the insert in mutation and in the writeInsert in mutationFn that works fine nah it doesnt work that subquery is messing with the query
const triedByUser = q.from({ tried: triedsCollection })
.where(({ tried }) => eq(tried.userId, user?.id))
const triedByUser = q.from({ tried: triedsCollection })
.where(({ tried }) => eq(tried.userId, user?.id))

Did you find this page helpful?