T
TanStack3y ago
fascinating-indigo

Handling optimistic update rollback when multiple mutations have been ran

const addIngredientToKitchenMutation = createMutation(() => ({
mutationFn: KitchenService.addIngredient,
onMutate: async (data) => {
const previousIngredients = queryClient.getQueryData(['kitchen-ingredients']);
await queryClient.cancelQueries({ queryKey: ['kitchen-ingredients'] })
queryClient.setQueryData(['kitchen-ingredients'], (old: KitchenIngredient[] | undefined) => {
if (old === undefined) {
return [{...data.ingredient, inStock: true}];
} else {
return [...old, {...data.ingredient, inStock: true}];
}
});

return { previousIngredients }
},
onSuccess: () => {
toast.success(`Added ingredient to your kitchen`);
},
onError: (error: any, _data, context) => {
toast.error(`Error adding ingredient to your kitchen ${error.message}`);

queryClient.setQueryData(['kitchen-ingredients'], context?.previousIngredients)
},
onSettled: () => {
queryClient.invalidateQueries({queryKey: ['kitchen-ingredients']});
},
}));
const addIngredientToKitchenMutation = createMutation(() => ({
mutationFn: KitchenService.addIngredient,
onMutate: async (data) => {
const previousIngredients = queryClient.getQueryData(['kitchen-ingredients']);
await queryClient.cancelQueries({ queryKey: ['kitchen-ingredients'] })
queryClient.setQueryData(['kitchen-ingredients'], (old: KitchenIngredient[] | undefined) => {
if (old === undefined) {
return [{...data.ingredient, inStock: true}];
} else {
return [...old, {...data.ingredient, inStock: true}];
}
});

return { previousIngredients }
},
onSuccess: () => {
toast.success(`Added ingredient to your kitchen`);
},
onError: (error: any, _data, context) => {
toast.error(`Error adding ingredient to your kitchen ${error.message}`);

queryClient.setQueryData(['kitchen-ingredients'], context?.previousIngredients)
},
onSettled: () => {
queryClient.invalidateQueries({queryKey: ['kitchen-ingredients']});
},
}));
I have this query, users typically quickly add ingredients, and on a slow network there may be multiple outgoing mutations at the same time. When they fail, the rollback function only rolls back the most recent context. Is there a way to roll back the first mutation that failed? The invalidateQueries eventually gets it if the API is still online but this can take a bit and the UI looks wonky on slow networks.
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?