Skip to content

Feature Request: Allow default values / computed fields on Persistence Handlers for QueryCollections #465

@chanidog

Description

@chanidog

Description

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions