react-nativeaxios

Axios Interceptors do not work sometimes when constante inside the hook code


I have the following code and the interceptors work great:

import axios from 'axios';
import { useDispatch } from 'react-redux';

const axiosPrivate = axios.create({
    baseURL: 'http://localhost:8080'
});

export default useAxiosPrivate = () => {
    const dispatch = useDispatch();

    useEffect(() => {
        const responseIntercept = axiosPrivate.interceptors.response.use(
            response => response,
            async (error) => {
                const prevRequest = error?.config;
                if (error.response?.status === 401 && error.response.data?.code === 'AccessTokenExpired' && !prevRequest.sent) {
                    prevRequest.sent = true;
                    const { refreshToken } = await getData();
                    return axios.post('http://localhost:8080/auth/refresh-token', { refreshToken })
                        .then(async (_) => {
                            return axiosPrivate(prevRequest);
                        })
                        .catch(async (error) => {
                            dispatch(login({ name: '', id: '' }));
                            return Promise.reject(error);
                        });
                }
                return Promise.reject(error);
            }
        );

        return () => {
            axiosPrivate.interceptors.response.eject(responseIntercept);
        }
    }, [])

    return axiosPrivate;
}

However, just out of curiosity, I tried to place the axiosPrivate, constant within the component code, like this:

export default useAxiosPrivate = () => {
    const axiosPrivate = axios.create({
        baseURL: 'localhost:8080'
    });

    const dispatch = useDispatch();
...}

When doing this, in some components the useAxiosPrivate hook interceptors work normally, in others they do not, as if they did not exist.

Could anyone tell me why this behavior?


Solution

  • When you put it in the hook, you’re creating a new axios instance every time the hook rerenders, which isn’t good.

    Your interceptors apply to the first instance only, since the useEffect only runs on mount. Your hook always return the latest created instance. So if the hook renders more than once you’re out of luck.