Search code examples
reactjsexpressreduxaxiosredux-thunk

Handling 401 unauthorised error in axios react-redux application


I want to handle 401 unauthorised error when my server outputs it , I want to dispatch a action in order to do that . I am seeing that many are using axios.interceptors how do I go about it . what are interceptors? Please explain in detail as to what it is and help me . Im new to react-redux framework. Here is my route handler in express:

router.get('/api/me', function(req, res) {

        if(req.user) {
            res.status(200).send({
                email : req.user.local.email,
                isCurrentUser: true
            });
        }else {
            res.status(401).send({
                isCurrentUser: false
            })
        }



})

here is my async action creator:

export const fetchCurrentUser =  () => {

    return async (dispatch) => {

        const res =  await axios.get(`${ROOT_URL}/me`); 
        if(res.status === 200) {
              dispatch({ type: types.YES_FETCH_CURRENT_USER, payload: res.data });
        }else if(res.status === 401) {
             dispatch({type: types.NO_FETCH_CURRENT_USER})
        }


    }

};

Solution

  • Interceptors are something within axios. You can compare interceptors to middlewares within express. You use interceptors to

    • intercept a request before it's being performed.
    • intercept a response before it's being handled as a Promise by you.

    Documentation about its usage can be found here.

    In your case you could do something like:

    const aiosInstance = axios.create();
    
    axiosInstance.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response.status === 401) {
          // dispatch something to your store
        }
    
        return Promise.reject(error);
      }
    )
    
    axiosInstance.get(`${ROOT_URL}/me`); 
    

    The above example does mean that you have to import your redux store instance to directly dispatch an action on that.

    Editted my answer based on the below conversation:

    Try:

    export const fetchCurrentUser =  () => async (dispatch) => {
      try {
        const res = await axios.get(`${ROOT_URL}/me`); 
    
        dispatch({ type: types.YES_FETCH_CURRENT_USER, payload: res.data });
      } catch (err) {
        dispatch({type: types.NO_FETCH_CURRENT_USER})
      }
    };