0

my problem is when i use custom axios aka axiosInstance, i only catch res.status == 200, when response is status 400, i can not take res.status and use it. My config custom axios:

import axios from "axios";
import { API_AUTH } from "./urlConfig";
import store from "../store";
import { authConstants } from "../store/actions/constants";

const token = localStorage.getItem("token") ? localStorage.getItem("token") : sessionStorage.getItem("token");

const axiosInstance = axios.create({
    baseURL: API_AUTH,
    headers: {
        Authorization: token ? `Bearer ${token}` : "",
    },
});

axiosInstance.interceptors.response.use(
    (res) => {
        return res;
    },
    (err) => {
        const { status } = err.response;
        if (status === 400) {
            localStorage.clear();
            store.dispatch({ type: authConstants.LOGOUT_SUCCESS });
        }
        return err;
    }
);
export default axiosInstance;

and this code when i use axios

import { authConstants } from "./constants";
import { LOGIN } from "../../helpers/urlConfig";
import authAPI from "../../helpers/authAPI";

export const login = (input) => {
    const { isRemember, ...inputUser } = input;

    return async (dispatch) => {
        dispatch({
            type: authConstants.LOGIN_REQUEST,
        });

        const res = await authAPI.post(LOGIN, {
            ...inputUser,
        });

        if (res.status === 200) {
            //do something OK when status code = 200.
        }
        if (res.status === 400) {
            //can not take res and check res.status
            console.log("res", res);            
        }
    };
};

Thanks for all help.

1 Answer 1

0

You probably need to handle the error using catch.

Usually I am doing something like this:

const res = await authAPI.post(LOGIN, { 
   ...inputUser
}).catch(error => ({
    status: error.response.status,
    data: error.response.data
}))

then you should be able to get res.status properly.

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

1 Comment

Thanks for your helps, it works fine. Good job bro.

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.