howard wolowitz
howard wolowitz

Reputation: 628

Not able to catch request error using axios

I have the following code, which is supposed to catch errors and read status code from there

 useEffect(async () => {
    try {
        const response = await apiSettingsSite.fetchProductsCalc();
        console.log(response)
    } catch (error) {
        console.log(error.response)
    }
},[])

but when 400 error happens i get null in the console from try block, code from catch is not even touched. Same with .then .catch

Upvotes: 0

Views: 140

Answers (3)

Dmitriy Mozgovoy
Dmitriy Mozgovoy

Reputation: 1597

It is not clear what code inside the fetchProductsCalc function and what Axios config was used.

To test Axios request on own endpoint, you can use the following code: Live sandbox

import React from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpAxios from "cp-axios";

function TestComponent(props) {
  const [cancel, done, result, err] = useAsyncEffect(
    function* () {
      return (yield cpAxios(props.url)).data;
    },
    { states: true, deps: [props.url] }
  );

  return (
    <div className="component">
      <div className="caption">useAsyncEffect demo:</div>
      <div>
        {done ? (err ? err.toString() : JSON.stringify(result)) : "loading..."}
      </div>
      <button className="btn btn-danger" onClick={cancel} disabled={done}>
        Cancel async effect
      </button>
    </div>
  );
}

Upvotes: 1

Ali Najafi
Ali Najafi

Reputation: 143

maybe you have a setting for axios i use like this:

const client = axios.create({ baseURL, json: true })

client.interceptors.response.use(undefined, async (err) => {
    return Promise.reject(err)
})

Upvotes: 1

Muhammad Ovi
Muhammad Ovi

Reputation: 1086

You need to create the async function inside useEffect, rather then passing async function to useEffect.

useEffect(() => {
  async function myFunc() {
    try {
      const response = await apiSettingsSite.fetchProductsCalc();
      console.log(response);
    } catch (error) {
      console.log(error.response);
    }
  };

  myFunc();
}, []);

Upvotes: 0

Related Questions