React-redux is dispatching an API action when clearly, the request sent back 401 error

I am trying to create a user authentication on my app. I created an api that will be called when ever a request is made on the app, so it can get the user’s data using the id I passed in the request object.

The issue am having now is that when that api is called, since a user hasn’t logged in, the token is null and the action (userLoaded) is not made to dispatch instead the getError and AuthError I caught in .catch should dispatch. This is turning authenticated to true, even though token is null, this is bad.

My redux console is showing that userLoaded was dispatched but getError and AuthError wasn’t dispatched.

This is the code…

The reducer
import {AUTH_ERROR, LOGIN_FAIL, LOGIN_SUCCESS, LOGOUT_SUCCESS, REGISTER_FAIL, REGISTER_SUCCESS, USER_LOADED, USER_LOADING} from '../action/types'

const initialState = {
  token : localStorage.getItem('token'),
  isAuthenticated : null,
  isLoading : false,
  user : null
}

export default function (state=initialState, action){

  switch (action.type) {

    case USER_LOADING:
      
      return {
        ... state,
        isLoading : true
      }

    case USER_LOADED:
      
      return {
        ...state,
        isAuthenticated :true,
        isLoading : false,
        user : action.payload
      }

    case LOGIN_SUCCESS:
    case REGISTER_SUCCESS:
      
      return {
        ...state,
        ...action.payload,
        isAuthenticated : true,
        isLoading : false
      }

    case AUTH_ERROR:
    case LOGIN_FAIL:
    case REGISTER_FAIL:
    case LOGOUT_SUCCESS:
      localStorage.removeItem('token') 
      
      return {
        ...state,
        token : null,
        isLoading : false,
        isAuthenticated : false,
        user : null
      }
  
    default:
      return state
  }



}

This is the action
import {AUTH_ERROR, LOGIN_FAIL, LOGIN_SUCCESS, LOGOUT_SUCCESS, REGISTER_FAIL, REGISTER_SUCCESS, USER_LOADED, USER_LOADING} from './types'

import {returnError} from './errorActions'


// So the first thing i have to do here is to check for a token and load it

export const userLoaded = () => (dispatch, getState) => {

  dispatch({type: USER_LOADING})

  // get the token from the current state

  const token = getState().auth.token

  // creating our header 

  const req = {
    headers : {"Content-Type":"application/json"}
  }

  // check if there's a token and if we have it, then we add it to the headers

  if(token){
    req.headers['x-auth-token'] = token
  }

  fetch('http://127.0.0.1:8000/auth/user', req)
  .then(res => res.json())
  .then(data => dispatch({
    type : USER_LOADED,
    payload : data
  }))
  .catch(err => {
    dispatch(returnError(err.response.data, err.response.status))
    dispatch({type: AUTH_ERROR})
  })
}