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

4 messages · Page 1 of 1 (latest)

glacial igloo
#

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");
        }
    });
azure onyx
#

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

mild pollen
#

Why can’t you modify the function itself?