T
TanStack8mo ago
other-emerald

Tracking mutations via mutation cache?

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?
3 Replies
rare-sapphire
rare-sapphire8mo ago
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),
})
}
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) });
...
}
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) });
...
}
other-emerald
other-emeraldOP7mo ago
brilliant and simple, this is what I needed thank you.
like-gold
like-gold7mo ago
You can also use the useMutationState to get the state of any mutation via mutationKey

Did you find this page helpful?