#Tracking mutations via mutation cache?

1 messages · Page 1 of 1 (latest)

manic kettle
#

Example: Have a row of records that could potentially have different mutations apply to them. Mutations can get called on these rows by a context menu that unrenders.

If I wanted to track the state of each of the rows and their related mutation, am I better manually tracking an array of Id's with error and loading states., or subscribing in a row component to the mutation cache?

solemn marsh
#

I believe the simplest approach would be to use individual mutation keys for each row, which means that the id should be baked into the mutationFn and not a parameter of the mutationFn. For example:

export function updateRowMutationKey(rowId: string) {
  return ['my', 'mutation', rowId]
}

export function useUpdateRow(rowId: string) {
  return useMutation({
    mutationKey: updateRowMutationKey(rowId),
    mutationFn: (data: Omit<Row, 'id'>) => updateRowInDb(rowId, data),
  })
}

Then in your component:

export function MyRowComponent({ rowId}: { rowId: string }) {
  const { mutate, ... } = useUpdateRow(rowId);

  // If the mutation isn't triggered from the row component, you can get its state with useMutationState or useIsMutating
  const isMutating = useIsMutating({ mutationKey: updateRowMutationKey(rowId) });
  ...
}
manic kettle
#

brilliant and simple, this is what I needed thank you.