0

I want to return error from react-query mutation service hook I've created here

const getMutationService = () => {
  return {
    editProfile: async (
      displayName: string,
      privateProfile?: boolean,
    ): Promise<AuthEditMeResponse | undefined> => {
      try {
        const result = await userApi.mePost({
          payload: {
            display_name: displayName,
            _private: privateProfile,
          },
        });
        return result;
      } catch (error) {
        console.log("User Edit Profile Error", error);
      }
    },
  };
};

const useUserProfile = () => {
  const queryClient = useQueryClient();
  const queryService = getQueryService();
  // const { data, isLoading } = useQuery('auth', queryService.login)
  const mutationService = getMutationService();

  const editProfileData = async (
    displayName: string,
    privateProfile?: boolean,
  ): Promise<AuthEditMeResponse | void> => {
    try {
      return await mutationService.editProfile(displayName, privateProfile);
    } catch (error) {
      console.log(error);
    }
  };

  return editProfileData;
};

export default useUserProfile;

Right now I am only returning the result, which is the successful result, however the API endpoint I am requesting to also returns error status codes that I must need and use for my front end component.

How can I return isLoading, data, or error from this getMutationService hook i've created? Instead currently its only returning successful responses to my component.

2 Answers 2

1

You can throw the errors inside the catch blocks, like this:

try { //... }
catch(e) {
  throw Error(e);
}

And when you invoke the function in your component, inside the catch block you can do something like:

try { //... }
catch(e) {
  setError(e.message);
}

to show the error message.

Sign up to request clarification or add additional context in comments.

Comments

0

The problem is that you are catching the error inside the mutation function. When you catch an error, e.g. for logging, it will be transformed into a resolved Promise. This has nothing to do with react-query, this is how promises (resp. try/catch with async-await) work.

react-query expects you to return a rejected Promise so that it can go into error state. To do this, you can either:

  • not catch errors in the mutationFn - just let them bubble up to react-query. This is the recommended approach. If you want error logging, use the provided onError callback.
  • re-throw the error after catching it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.