Search code examples
reactjstypescripterror-handlingaxiosreact-query

net::ERR_CONNECTION_REFUSED and Uncaught Error when using Axios with TanStack-Query useMutation (asyncMutation)


On my app i tried to implement a simple login, which is working fine if my server is running. But when my backend is offline, i try to catch the error and show it to the user. But i still get unwanted errors in my console, even if i wrapped everything with try/catch and handle those errors. In this case i do not understand why i can't catch the error in my apiLoginMutation, but get a uncaught error in my console.

My used setup

  • Vite (with TypeScript)
  • React
  • TanStack Query
  • TanStack Router
  • Axios
  • React Hook Form

My console output

That's how i set everything up.

AuthPage Component

const AuthPage = () => {

    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm<LoginFormSchemaType>({
        resolver: zodResolver(LoginFormSchema),
        defaultValues: {
            email: "",
            password: "",
        },
    });

    const { mutateAsync: apiLoginMutation } = useMutation({
        mutationFn: APILogin,
        onSuccess: () => {
            //Handle the redirect
        },
        onError: (error: AxiosError) => {
            console.log("Error in onError: " + error.message);
        },
    });

    const onSubmit = async (data: LoginFormSchemaType) => {
        try {
            apiLoginMutation(data);
        } catch (error) {
            console.log("Error on apiLoginMutation call: " + error); //This never gets called! 
        }
    };

    return ( //JSX Stuff as Form)
};

http.ts

import axios from "axios";

const API_URL = "http://localhost:8000/api";

export type LoginData = {
    email: string;
    password: string;
};

export async function APILogin(formData: LoginData) {
    try {
        const { data } = await axios.post(
            `${API_URL}/login`,
            { email: formData.email, password: formData.password },
            { withCredentials: true }
        );
        axios.defaults.headers.common["Authorization"] = `Bearer ${data.token}`;
    } catch (err) {
        throw err;
    }
}

As said above, i've tried to wrap everything in try/catches, but never got to the point, that no error is shown to my console. Also tried to build my app (with vite) and run as preview. All errors are still visible, because i've read about some DEVMODE Parts to show everytime, but they appeared even on the production build, so i can't confirm those theories (<--- relates mostly to the POST http://localhost:8000/api/login net::ERR_CONNECTION_REFUSED error in console)


Solution

  •         try {
                apiLoginMutation(data);
            } catch (error) {
                console.log("Error on apiLoginMutation call: " + error); //This never gets called! 
            }
    

    This part is not catching any errors because apiLoginMutation is async, you need to await it.

            try {
                await apiLoginMutation(data);
            } catch (error) {
                console.log("Error on apiLoginMutation call: " + error); //This never gets called! 
            }
    

    This should make a difference.