Search code examples
reactjsreact-querytanstackreact-query

How to handle error so that it stops function execution


It goes to the onError in the mutation, however in the try catch the next response has a status of 200 so it does not execute the catch method. What should I do so that if it goes to onError, it goes to catch. I am also open to any solution that can correctly return/ end the function

const useValidatePassword = () =>{  
    return useMutation({
      mutationFn: async (data: any) => {
          const body: validatePasswordPayload = 
            {
               UserName: data.username,
               Password: data.currentPassword,
            };
         await apiAccountSettings.validatePassword(tenantName, body);
        }
      ,
      onSuccess: () => {
        return true
      },
      onError: (data) => {
        toast.error(t('Current password is incorrect'));
      },
      mutationKey: ['ValidatePassword', { tenant: tenantName }],
    });
}
       const {mutate: validatePassword, error} = useValidatePassword();

      Somefn()=>{
        try {
            await validatePassword(validatePayload);
        } catch (error) {
            toast.error(t("Something went wrong"));
            return
        }
      }

Solution

  • By throwing the error in the onError callback, you ensure that error is propagated to try-catch block.

    new Promise wrapper around validatePassword call ensures that try-catch block can await result of mutation and catch any errors that are thrown.

    const useValidatePassword = () => {
      return useMutation({
        mutationFn: async (data: any) => {
          const body: validatePasswordPayload = {
            UserName: data.username,
            Password: data.currentPassword,
          };
          await apiAccountSettings.validatePassword(tenantName, body);
        },
        onSuccess: () => {
          return true;
        },
        onError: (error) => {
          toast.error(t('Current password is incorrect'));
          throw error; // Throw the error to propagate it
        },
        mutationKey: ['ValidatePassword', { tenant: tenantName }],
      });
    };
    
    const { mutate: validatePassword } = useValidatePassword();
    
    const Somefn = async () => {
      try {
        await new Promise((resolve, reject) => {
          validatePassword(validatePayload, {
            onSuccess: resolve,
            onError: reject,
          });
        });
      } catch (error) {
        toast.error(t("Something went wrong"));
        return;
      }
    };