Home > Back-end >  axios error react interceptors request is not a function
axios error react interceptors request is not a function

Time:07-10

i have a configuration with axios i am testing a feature to receive a list of students from an api, the problem is that it sends me an error:

TypeError: constants_api_constants__WEBPACK_IMPORTED_MODULE_1_.default.interceptors.request is not a function

For my axios configuration I use:

const options.GET_ALL_STUDENTS = {
  method: "GET",
  url: "/Student",
}
const BASE_API_URL = "https://localhost:7072/api";
const api = axios.create({
  baseURL: `${BASE_API_URL}`,
});

const getStudents = () => {
  return api.interceptors.request(options.GET_ALL_STUDENTS).use(
    function request(success) {
      return success;
    },

    function error(err) {
      return err;
    },
  );
};

How I resolve my promise, (without interceptor this work fine):

function* fetchStudents() {
  try {
    const result1 = yield call(getStudents);
    const studentList = createStudentListAdapter(result1.data);
    yield put(fetchStudentsSuccess(studentList));
  } catch (error) {
    yield put(fetchStudentsFailure());
  }
}

CodePudding user response:

Interceptors are used to intercept any request/response before it goes to try/catch.

const getStudents = async () => {
  try {
    const res = await api(options.GET_ALL_STUDENTS);
    // logic
  } catch (e) {
    // handle error
  }
};

Interceptor

api.interceptors.request.use(
  (request) => {
    console.debug("Request", request.url);
    return request;
  },
  (error) => {
    console.debug("Request Failed", error.request.data.message);
    return Promise.reject(error);
  },
);
  • Related