This is my first question, so let me know how I can improve.
I have the following axios fetch function:
export enum RequestMethod {
GET = 'GET',
POST = 'POST',
PUT = 'PUT',
PATCH = 'PATCH',
DELETE = 'DELETE',
}
export const fetchAxiosAPI = async (
url: string,
method: RequestMethod,
data = {},
options = {}
) => {
let result;
try {
result = await axios({
method,
url: `${process.env.REACT_APP_API_URL}/${url}`,
data,
...options,
validateStatus: () => {
return true;
},
}).then(response => response.data);
} catch (err) {
return null;
}
const errorStatus = result.error.status;
if (errorStatus === 401) {
localStorage.removeItem('access_token');
history.push('/login');
}
if (errorStatus === 404) {
history.replace(NOT_FOUND);
}
if (errorStatus === 500) {
history.replace(INTERNAL_SERVER_ERROR);
}
return result;
};
It looks ugly, uses await and then (which we shouldn't use).
I have two questions:
- How can I pass a typescript generic into this function as a parameter that will infer typescript typings for the response of API call (Promise)? I found and example using axios[methodName] like:
axios.get<User[]>(url)
But haven't found a method to pass generic using general axios method like provided in my code example.
- How to handle error statuses, catch block and await/then - use 1 of them? Basically, how to rewrite
fetchAxiosAPI
function.