TanStackT
TanStack3y ago
4 replies
brilliant-lime

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;
};


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");
        }
    });
Was this page helpful?