DEV Community

Discussion on: You Don't Need Axios

Collapse
 
joshuaamaju profile image
Joshua Amaju

One reason to avoid axios, difficult to handle errors.

Collapse
 
adaptive-shield-matrix profile image
Adaptive Shield Matrix

How is it more difficult to handle than fetch?

You can even overwrite/define then it throws errors
pipedream.com/community/t/faq-how-...

Thread Thread
 
joshuaamaju profile image
Joshua Amaju

it's not about when it throws, it's how it handles errors. It hides the response in error.response.data, which becomes a big issue when dealing with typescript.

Thread Thread
 
adaptive-shield-matrix profile image
Adaptive Shield Matrix

How is accessing the response with error.response.data in typescript a big problem?

Thread Thread
 
joshuaamaju profile image
Joshua Amaju • Edited

When using asyn/await you loose all types, so you have to do

if (isAxiosError(error)) {
  let err = error.response?.data?.whatever
}
Enter fullscreen mode Exit fullscreen mode

And I just don't like writing error.response?.data?.whatever in general. I generally prefer dealing with Response.

And there's no way to conditionally tell axios to not parse responses. One big reason to not use axios is because of the all or nothing behaviour. You have build a client for each scenario (which is unrealistic)

Thread Thread
 
adaptive-shield-matrix profile image
Adaptive Shield Matrix

You can type axios, example:
await axios.post<EventType[] | { errorMessage: string }>(urlApiCmdPublic, cmd)
so I would not count that as a downside. Fetch in comparison does not have any types at all.

"no way to conditionally tell axios to not parse responses" - that's a fair point,
but its relevant only if using some non-http/rest APIs - which to be fair should be pretty rare.

I agree with you, that axios is mostly designed to consume http/rest apis with good developer experience
and having the niche use-case of calling lower level binary apis is best served using lower level tools like fetch.

Thread Thread
 
joshuaamaju profile image
Joshua Amaju • Edited

await axios.post<EventType[] | { errorMessage: string }>(urlApiCmdPublic, cmd) only works for non-error responses.

Fetch in comparison does not have any types at all

Not exactly true, you get aResponse which makes sense. And then you can convert to json and do validation i.e using zod schema.parse(await response.json()) to get a concrete type. Which is a much better approach than what axios offers

Some comments have been hidden by the post's author - find out more