Harkirat Saluja Harkirat Saluja - 1 month ago 18
React JSX Question

How to handle >400 responses in api calls from redux app?

Currently I using

fetch
to make api calls in my redux app.

I tried building a middleware api :-

export function api(endpoint,method,isAuth=false,body=null,multiPart=false,initToken=null)
{
let promise = null
let myHeaders = new Headers();
if(!multiPart){
myHeaders.append("Content-Type", "application/json");
}


if(isAuth){
//if authorizations is needed adding header
const accessToken = authentication.getAccessToken()
myHeaders.append("Authorization",accessToken)
}

if(initToken){
// in case of initToken adding to Authorization
console.log("here"+initToken)
myHeaders.append("Authorization",initToken)
}

let myInit = { method: method,headers: myHeaders};

myInit['method'] = method
myInit['headers'] = myHeaders

if(body){
myInit['body'] = body
}


let request = new Request(constants.BASE_URL+endpoint,myInit);
promise = fetch(request)

return promise
}


I inject the above in my thunk with extraArguments

export default function configureStore(initialState) {
const store=createStore(
rootReducer,
initialState,
compose(
applyMiddleware(thunk.withExtraArgument(api),createLogger()),
DevTools.instrument()
))
return store
}


Following in my action which calls the api:-

export function fetchEmployeeInformation(){
return (dispatch,getState,api) => {
const endPoint = '//url'
const method = 'GET'
const isAuth = true
const promise = api(endPoint,method,isAuth)
promise
.then(response =>
response.json().then(json => ({
status:response.status ,
json
})
))
.then(
({ status, json }) => {
if( status >= 200 && status < 300) {
//success
}
if (status >= 400 ) {
//throw error
}
},
err => {
console.log("error"+err);
}
);
}
}


So my question here is is there any package like $http in angularjs which I can use with my react-redux app. I mean if status code is within range 200-299 it should make it as success or else throw an error.

With fetch I see it does not care much about the code and I have to specifically check whether the code range is above >400 and then throw error.

Is there any better way to handle this?

Answer

Library axios has similar flow as Angular $http including requestInterceptor and responseInterceptor. Read More docs