Repository navigation
|
Is it possible to modify the vars passed in a mutation inside onMutate or any other side effects that I'm not aware of? Consider this mutation hook type VarType = {
lastCellId: number;
position: number;
}
export function useInsertCell() {
const queryClient = useQueryClient();
return useMutationWithAuth(insertCell, {
onMutate: async (vars: VarType) => {
await queryClient.cancelQueries({
queryKey: ["cells", vars.pageId],
});
//I will perform some sorting here based on the query data to recalculate the official position of my newly added cell based on lastCell id
const cachedCells: Cell[] = queryClient.getQueryData(["cells", vars.pageId]) || [];
const newCell = {...vars, id: undefined}
//Pretending the calculation is done
//I want to update var.position here
//I understand that this can be mutated, but isn't that an anti pattern?
vars.position = cachedCells.find(c=>c.id === undefined).position;
return {
previousCells: queryClient.getQueryData([
"cells",
vars.pageId,
]),
pageId: vars.pageId,
};
},
});
}Is there anyway to "mutate" the mutation variable so I can send the correct payload to my API endpoint? Updating it directly seems like an anti pattern Or do I have no choice but to do all of it before the mutation? I'm essentially trying to avoid using query client on my components, for SOC purposes. |
Replies: 5 comments 1 reply
|
I have a similar need. I'm squashing consecutive paused mutations (same key + entity) into one before they flush, merging their variables in onMutate. The only way I've found to propagate merged variables to mutationFn is mutating the object in-place: This works because Mutation.execute() shares the same variables reference between onMutate and mutationFn via closure. But it feels fragile since it's relying on an implementation detail. Would be great to have some guidance from the TanStack team on this one :) |
|
I also have this question. We're generating a uuid and using it in the mutationFn. We could do this at the call site of the mutation, but I was just curious if it would be supported to to this in the onMutate instead. |
|
What are you doing with variables in onMutate that cant be done in the mutationFn? You can bind it in a closure, use something like useCallback, to ensure it's closed over anything we need. Plus, we pass in the query Client via |
This comment was marked as low quality.
This comment was marked as low quality.
|
I'm gonna close this issue. directly editing the |
I'm gonna close this issue. directly editing the
variablesinside aonMutateis regarded as an anti-pattern. the fact it "works" is an implementation detail, not a part of the API contract of TanStack Query.