T
TanStack2y ago
ambitious-aqua

Best practice for dealing with mutation function that doesn't error

Hey all, I have a useMutation that wraps a function that returns a type like follows:
type Return = {
status: "success";
data: string;
} | {
status: "error";
errors: SomeErrorType;
};
type Return = {
status: "success";
data: string;
} | {
status: "error";
errors: SomeErrorType;
};
The difficulty is I want to use React-Query's features like status, auto-error retrying, etc. To make this work, I've had to wrap the mutation function in something that checks for status === "error" and then throw an error so React-Query sees it as such. Anyone have a cleaner idea for this?
onst { status, data, isLoading, mutate } = useMutation({
mutationFn: async () => {
const result = await someMutationFunction();

// If successful, return data
if (result.status === "success") return result.data;

// Something unexpected happened
setError("name", { message: "Something went wrong" });
throw new Error("Unexpected error");
}
});
onst { status, data, isLoading, mutate } = useMutation({
mutationFn: async () => {
const result = await someMutationFunction();

// If successful, return data
if (result.status === "success") return result.data;

// Something unexpected happened
setError("name", { message: "Something went wrong" });
throw new Error("Unexpected error");
}
});
3 Replies
optimistic-gold
optimistic-gold2y ago
Probably cleaner to use the onError callback to perform your setError but other than that looks fine If there are multiple mutations like this then you could put the check for error inside a separate method e.g. throwIfErrorStatus(result) to call from any mutation
flat-fuchsia
flat-fuchsia2y ago
Why can’t you modify the function itself?
ambitious-aqua
ambitious-aqua2y ago
why is setError needed at all?
const { status, data, isLoading, mutate } = useMutation({
mutationFn: async () => {
const result = await someMutationFunction();

// If successful, return data
if (result.status === "success") return result.data;

// Something unexpected happened
throw new Error("Unexpected error");
}
});
const { status, data, isLoading, mutate } = useMutation({
mutationFn: async () => {
const result = await someMutationFunction();

// If successful, return data
if (result.status === "success") return result.data;

// Something unexpected happened
throw new Error("Unexpected error");
}
});

Did you find this page helpful?