tRPC setData hook doesn't have access to all data for optimistic ui updates

512 Views Asked by At

I'm building out mutations with tRPC and React Query that optimistically update my UI when a new item is added, but I'm running into a problem.

The query that I'm updating expects a certain number of properties that are either auto-generated, such as an ID, or relationships from the database, such as tags etc. Is there a type-safe way around this so I can use the data that is passed into the onMutate callback without having to create a lot of temp data to satisfy the type constraints? This is what my onMutate function is looking like:

onMutate: (data) => {
      const previousJobs = utils.jobs.getAll.getData();
      if (previousJobs) {
        utils.jobs.getAll.setData((() => undefined)(),
        [...previousJobs, { ...data, status: JobStatus.OPEN, priority: JobPriority.NO_PRIORITY, id: "temp", created_at: new Date(), updated_at: new Date(), team_id: "temp", user_id: "temp" }]
        ); 
      }
    },

And I'm seeing this error:

 Type '{ status: "OPEN"; priority: "NO_PRIORITY"; id: string; created_at: Date; updated_at: Date; team_id: string; user_id: string; salary: number; title: string; office_type: string; description: string; due_date: Date; }' is missing the following properties from type '{ user: User & { view: { state: ViewState; }[]; }; _count: { tags: number; candidates: number; }; tags: { id: string; value: string; color: string; }[]; }'
1

There are 1 best solutions below

0
On BEST ANSWER

This is one of the drawbacks of optimistic updates. You have to replicate the logic that the server would do on the client, ahead of time.

I'm going into that here: https://tkdodo.eu/blog/mastering-mutations-in-react-query#optimistic-updates

If you can render your UI properly without those fields, then those fields should likely be optional in your type definition. If they are mandatory, like an id field, you have to create fictional values in the onMutate callback.