Feature Request: Allow default values / computed fields on Persistence Handlers for QueryCollections #465
Send to my agentDescription#
When using queryCollectionOptions, inserts must fully satisfy the return type of the queryFn. This makes it hard to work with cases where some fields (like id or completed) should be auto-generated or defaulted like inserts to databases.
const [todos, setTodos] = React.useState([
{ id: 1, completed: false, title: 'Todo' },
]);
const todoCollection = createCollection(
queryCollectionOptions({
// ... other options
queryFn: async () => todos,
onInsert: async ({ transaction }) => {
const newItems = transaction.mutations.map((m) => m.modified);
setTodos((prev) => {
let idCounter = nextId;
// only the title is required to insert
const todosToAdd = newItems.map((item) => ({
id: idCounter++,
title: item.title,
completed: false,
}));
setNextId(idCounter);
return [...prev, ...todosToAdd];
});
},
})
);
// ...
function addTodo(title: string) {
todoCollection.insert({
title: 'New Todo',
});
}
// ^ is missing the following properties from type
I’m forced to provide id and completed manually even though they should be derived internally.
Minimal reproduction:#
https://stackblitz.com/edit/github-4dmuepcv?file=src%2Froutes%2Findex.tsx
Proposed solution#
Support different schemas for insert, update, and delete? operations:
- Insert schema: allows partial objects and applies defaults/computed values (title required, id + completed handled internally).
- Update schema: validates only fields that are allowed to be modified (title, completed).
- Delete: idk about delete if it needs data to delete i could be wrong tho
or just parameterize Persistence Handlers but the library uses standard schemas so i assume its not that simple but it would be a lot nicer
Thank you so much for this library!
usually the database handles defaults.
queryCollectionswont know what the defaults so optimistic updates would be impossible i think
Sign in to join this conversation.
Has anyone found a solution to handle this kind of situation? I think that in these cases, the data received from the API and the data being inserted can clearly be different.