T
TanStack•2w ago
sensitive-blue

Updates not persisting

Hi, I'm new to DB and I'm stuggling to get this simple CRUD setup working.
export const sessionsCollection = createCollection(
queryCollectionOptions({
queryKey: [QUERY_KEY_OWNED_SESSIONS],
queryFn: async () => listSessionsServerFn({}),
schema: ActiveSessionSchema,
queryClient,
getKey: (item) => item.id,
onInsert: async ({ transaction }) => {
const newItem = transaction.mutations[0].modified;
const saved = await insertSessionServerFn({ data: newItem });
return { upsert: [saved] };
},
onUpdate: async ({ transaction }) => {
const mutation = transaction.mutations[0].modified;
console.log('mutation', mutation);

const updated = await updateSessionServerFn({ data: mutation });
return { upsert: [updated], refetch: false };
},
onDelete: async ({ transaction }) => {
const id = transaction.mutations[0].key;
await deleteSessionServerFn({ data: { sessionId: id } });
return { remove: [id], refetch: false };
},
})
);

... later
const tx = sessionsCollection.update('id_12345' (draft) => {
return {
...draft,
...form.getValues(),
};
});
await tx.isPersisted.promise;
export const sessionsCollection = createCollection(
queryCollectionOptions({
queryKey: [QUERY_KEY_OWNED_SESSIONS],
queryFn: async () => listSessionsServerFn({}),
schema: ActiveSessionSchema,
queryClient,
getKey: (item) => item.id,
onInsert: async ({ transaction }) => {
const newItem = transaction.mutations[0].modified;
const saved = await insertSessionServerFn({ data: newItem });
return { upsert: [saved] };
},
onUpdate: async ({ transaction }) => {
const mutation = transaction.mutations[0].modified;
console.log('mutation', mutation);

const updated = await updateSessionServerFn({ data: mutation });
return { upsert: [updated], refetch: false };
},
onDelete: async ({ transaction }) => {
const id = transaction.mutations[0].key;
await deleteSessionServerFn({ data: { sessionId: id } });
return { remove: [id], refetch: false };
},
})
);

... later
const tx = sessionsCollection.update('id_12345' (draft) => {
return {
...draft,
...form.getValues(),
};
});
await tx.isPersisted.promise;
I can't see why the update is not mutating the record on the collection or calling the onUpdate() callback. The object is valid. Any ideas? Any help would be much appreciated. Thank you in advance.
2 Replies
fair-rose
fair-rose•2w ago
Hey @Jingle Bells the draft needs to be mutated, you cant return a new object. We do this to track exactly what has and has not changed.
const tx = sessionsCollection.update('id_12345' (draft) => {
draft.something = form.something
// ...
});
const tx = sessionsCollection.update('id_12345' (draft) => {
draft.something = form.something
// ...
});
sensitive-blue
sensitive-blueOP•2w ago
@samwillis thanks very much. That works! 🔥

Did you find this page helpful?