#Optimistic without full object

4 messages · Page 1 of 1 (latest)

frigid radish
#

How to use the optimistic hook while mutating without passing the full object because it's asking for things like _createdTime

oblique mothBOT
#

Hi @frigid radish. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You do not need to pass the full object (including system fields like _creationTime or _id) to your mutation or optimistic update. When using optimistic updates in Convex, you only need to provide the fields relevant to your update. The system fields are managed by Convex itself.

For example, if you want to optimistically add a message, you can create a temporary object with just the fields you have, and generate placeholder values for system fields like _id and _creationTime (e.g., using crypto.randomUUID() and Date.now()). These will be replaced by the real values once the server mutation completes. Here’s a pattern from the official docs:

const sendMessage = useMutation(api.messages.send).withOptimisticUpdate(
  (localStore, args) => {
    const { channel, body } = args;
    const existingMessages = localStore.getQuery(api.messages.list, { channel });
    if (existingMessages !== undefined) {
      const now = Date.now();
      const newMessage = {
        _id: crypto.randomUUID() as Id<"messages">,
        _creationTime: now,
        channel,
        body,
      };
      localStore.setQuery(api.messages.list, { channel }, [
        ...existingMessages,
        newMessage,
      ]);
    }
  },
);

You do not need to pass the full object to the mutation itself—just the fields your mutation expects (e.g., channel and body). The optimistic update is only for local UI responsiveness and will be rolled back once the real data arrives from the server. If your mutation or schema requires certain fields, you can use TypeScript’s Partial type or a helper like partial from convex-helpers to allow partial updates, especially for patch-like mutations Stack: Argument Validation without Repetition.

#

If you see errors about missing fields, make sure your optimistic update is only updating the local query result, not the mutation arguments. The mutation itself should only require the fields it actually needs to perform the update.

Summary:

  • For optimistic updates, create a temporary object with the fields you have and placeholder values for system fields.
  • For mutations, only pass the fields required by your mutation handler.
  • Use helpers like Partial or partial for patch-style updates if needed.

References:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: