Not able to get the response code in react js axios - reactjs

Here is my common method for post:
export const post = (url: string, param: any) => {
const CancelToken = axios.CancelToken; // axios cancel request
const source = CancelToken.source();
post.prototype.source = source;
return axios.post(url, qs.stringify(param), { cancelToken:
source.token }).then((resp) => resp);
};
Here is my post method:
const postMyMethod = async () => {
await postMd(params)
.then((response: any) => {
console.log(response) // in response not getting status code
})
};
Below is the error handling code, how to get the response status code(ex: 200, 400...):
axios.interceptors.response.use(
function (response) {
if (response && response.data && response.data.Code && response.data.Message) {
message.error(response.data.Message);
response.data = null;
}
return response;
},
function (error) {
if (error.response && error.response.data && error.response.data.Code && error.response.data.Message) {
message.error(error.response.data.Message);
} else {
message.error('Unknown error, please check your network ~');
}
return error;
}
);
Finally if I do:
console.log(response)
Getting: Error: Request failed with status code 400
How to get the status code to do the if condition in the postMyMethod()?
I want to do like this in the postMyMethod(). How to achieve this?
if(response.status === 200){
// do something
}
if (respone.status === 400){
// do something
}

The error is because you are not using a catch() block in your postMyMethod function. You should add it so it will handle any error response. It will look something like this:
const postMyMethod = async () => {
await postMd(params)
.then((response) => {
console.log(response)
}).catch((err) => {
console.log(err.response.statuscode);
});
};
If response code 400 is something specific you want to handle differently in your function, your catch() block will be:
const postMyMethod = async () => {
await postMd(params)
.then((response) => {
console.log(response)
}).catch((err) => {
if (err.response.statuscode == 400) {
console.log(err);
} else {
console.log("something else");
}
});
};
You can read more about the catch() method here.

Finally got it:
.then((response: any) => {
console.log(response.response.status);
console.log(response.response.data);
})
or need to add below code under function error > if condition
return error.response;
Now getting the response status and failure data.

Related

Return the fetch response from another file

I am trying to call a function that calls fetch to an API from a React component in a separate file and am not finding the correct solution to get the correct response back.
When I debug, the result returns before the updateAccount function has completed and the final result is never returned to my update function.
Inside the fetch, the API returns the correct response whether it is successful or has validation errors and those results are correctly assigned to result.success and result.errors but the result doesn't get returned from the function so that the caller can make use of those values.
Inside of my React component:
import { updateAccount } from '../services/requests';
...
const update = (account: EditAccountModel) => {
const result = updateAccount(account);
if(result.errors.length > 0) {
// will notify of errors
console.log(result.errors); // is an empty array instead of validation errors
} else {
// will notify of success
console.log(result.success); // is an empty string instead of success message
}
}
...
My request file
export const updateAccount = (account: EditAccountModel | undefined): EditAccountResponseModel => {
const result = new EditAccountResponseModel();
fetch(baseUrl, {
method: 'PUT',
body: JSON.stringify(account),
headers
})
.then(response => {
if (!response.ok) {
return Promise.reject(response);
}
result.success = `${account?.name} was updated successfully!`
})
.catch(error => {
if (typeof error.json === "function") {
error.json().then(jsonError => {
result.errors.push(jsonError);
}).catch(genericError => {
result.errors.push(genericError);
});
}
});
return result;
}
The result reassignment happens inside then catch but it won’t be affective in the way you expected. The guaranteed way to return correct result is via a callback() passed to your updateAccount() if you could afford it:
export const updateAccount = (
account: EditAccountModel | undefined,
callback: Function
): EditAccountResponseModel => {
const result = new EditAccountResponseModel();
fetch(baseUrl, {
method: 'PUT',
body: JSON.stringify(account),
headers
})
.then(response => {
if (!response.ok) {
return Promise.reject(response);
}
result.success = `${account?.name} was updated successfully!`
callback(result);
})
.catch(error => {
if (typeof error.json === "function") {
error.json().then(jsonError => {
result.errors.push(jsonError);
callback(result);
}).catch(genericError => {
result.errors.push(genericError);
callback(result);
});
}
});
}
And inside your React component:
const update = (account: EditAccountModel) => {
const handleResult = (res) => {
// your result callback code
// ...
};
updateAccount(account, handleResult);
// ...
}
Alternative way that keeps your current structure is to change your current updateAccount() to an async function, then return await fetch().
You need to wait for the response . I'll let read more about how Promise work in JavaScript.
I wouldn't code updateAccount the same way you did, especially where you use the variable result and update it inside the flow of the promise (you really don't need that). You're also using React so you can use the state to store and update the result of the update function. But let's fix your problem first:
export const updateAccount = async (account: EditAccountModel | undefined): EditAccountResponseModel => {
const result = new EditAccountResponseModel();
await fetch(baseUrl, {
method: 'PUT',
body: JSON.stringify(account),
headers
})
.then(response => {
if (!response.ok) {
return Promise.reject(response);
}
result.success = `${account?.name} was updated successfully!`
})
.catch(error => {
if (typeof error.json === "function") {
error.json().then(jsonError => {
result.errors.push(jsonError);
}).catch(genericError => {
result.errors.push(genericError);
});
}
});
return result;
}
First make your function updateAccount async then await the result of the promise.
Now the same thing for the function update:
const update = async (account: EditAccountModel) => {
const result = await updateAccount(account);
if(result.errors.length > 0) {
// will notify of errors
} else {
// will notify of success
}
}

React websocket message coming before response

I am having a case now with websockets.
I am using Promise to read response and message from socket. Afterwards I compare them and if they have the same id, it goes through.
However, most of the time socket message is arriving (fast) before response and as a result I cannot compare socket message with response id.
const init = {
get(...args) {
return request.get(...args);
},
post(...args) {
// return request.post(...args)
return new Promise((resolve, reject) => {
let response = {};
request
.post(...args)
.then((res) => {
console.log("RESPONSE====>", res);
response = res;
})
.catch((err) => reject(err));
webSocket.onmessage = (mes) => {
try {
// console.log(JSON.parse(mes.data))
let { correlation_id: socketId, status_code } = JSON.parse(mes.data);
console.log("MESSAGE====>", socketId);
if (socketId === response.message) {
resolve(response);
} else if (status_code > 300) {
reject({ status_code });
}
} catch (e) {
console.log(e);
}
};
// resolve(response)
});
}
export default init;
Above is my code for axios requests. If you know how to resolve it, kindly help here.

How do I get the HTTP response code from a successful React query?

How do I get the status code from a successful React query?
This is my custom hook:
const validateIban = async (accountId, encodedIban) => {
await axios
.post(`${CUSTOMER_PORTAL_API}/policy/accounts/${accountId}/iban/${encodedIban}`)
};
export function useValidateIban(accountId) {
return useMutation(encodedIban => validateIban(accountId, encodedIban));
}
And this is where I use the hook with mutate:
const validateIbanQuery = useValidateIban(accountId)
validateIbanQuery.mutate(encodeURIComponent(iban), {
onSuccess: () => {
******HERE I WANT THE STATUS CODE (204, 202 e.g.)******
},
onError: (error) => {
if (error.response.status === 400) {
....
}
if (error.response.status === 403) {
....
}
}
})
The first parameter of the onSuccess callback is the AxiosResponse:
axios.post("/api/data", { text }).then(response => {
console.log(response.status)
return response; // this response will be passed as the first parameter of onSuccess
});
onSuccess: (data) => {
console.log(data.status);
},
Live Demo

Clearing an item from AsyncStorage - React native

I'm new to react native currently i'm working on a project that needs to update a specific value in async storage. I tried by clearing an item from Asyncstorage using this code await AsyncStorage.removeItem(key); but when i used it console throws an error like this 'await' is only allowed within async functions . But i'm using an async function
const getExceedCountData = async () => {
const token = await AsyncStorage.getItem("#userToken")
const exceedcount = await AsyncStorage.getItem("#exceedCount")
if(!exceedcount){
try {
setLoading(true)
axios
.get(constants.BASE_URL + "getexceedcount?token=" +token)
.then(response => {
if(response.data.status == 1){
try {
await AsyncStorage.removeItem("#exceedCount");
}
catch(exception) {
console.log('Error Occured');
}
AsyncStorage.setItem("#exceedCount", response.data.result);
setExceedCount({ value:response.data.result, error: '' })
}
})
.catch(error => {
console.log(error);
});
} catch(error) {
console.log(error);
}
}else{
setExceedCount({ value:exceedcount, error: '' })
}
}
I don't know why this issue occured. Any help is appreciable.
You need to notate the function as async.
.then(async (response) => {
if(response.data.status == 1){
try {
await AsyncStorage.removeItem("#exceedCount");
}
catch(exception) {
console.log('Error Occured');
}
AsyncStorage.setItem("#exceedCount", response.data.result);
setExceedCount({ value:response.data.result, error: '' })
}
})
The scope of the function inside .then is not declared as async. This should fix your problem:
.then(async response => {
if(response.data.status == 1){
try {
await AsyncStorage.removeItem("#exceedCount");
} catch(exception) {
console.log('Error Occured');
}
AsyncStorage.setItem("#exceedCount", response.data.result);
setExceedCount({ value:response.data.result, error: '' })
}
})

Why 401 errors is not getting caught with the fetch function in reactJS?

I am using redux approach in react js.I am calling getRolesPagination()
with service getRolesPagination() and pass handleResponse() in service to catch response/error.
It is working fine but when the server respond with 401 status error it doesn't catch the error.
I have to catch it to log out user because if user token get invalidate then the server responds with 401 status and
"{error :Unauthorized}"
function getRolesPagination(page, filter, sort, pageSize){
return dispatch => {
dispatch(request())
roleService.getRolesPagination(page, filter, sort, pageSize)
.then(
response => {
dispatch(success(response));
},
error => {
dispatch(failure(error));
dispatch(alertActions.error(error));
}
);
};
function request() { return { type: adminConstants.PAGINATION_ROLES_REQUEST } }
function success(response) { return { type: adminConstants.PAGINATION_ROLES_SUCCESS, payload:response } }
function failure(error) { return { type: adminConstants.PAGINATION_ROLES_FAILURE, payload:error } }
}
roleService.getRolesPagination function:
function getRolesPagination(page, filter, sort, pageSize){
const requestOptions = {
method : 'GET',
headers : authHeader()
};Why 401 errors is not getting caught with the fetch function in reactJS?
return fetch(baseUrl+'roles?page='+page+'&filter='+filter+'&sort='+sort+'&pageSize='+pageSize, requestOptions).then(handleResponse);
}
handleResponse function:
export function handleResponse(response) {
return response.json().then(data => {
if (!response.ok) {
if (response.status === 401) {
localStorage.removeItem('user');
window.location.reload(true);
}
const error = (data && data.error) || response.statusText;
return Promise.reject(error);
}
return data;
});
}
please check the status of the response, 401 is a valid server response it won't go to catch block
fetch(request)
.then(function(response) {
if (response.status !== 200) {
/*your code */
}else{
throw new Error(response.status)
}
})
.catch(function(error) {
/*logout logic*/
});

Resources