Is there any reasons to use axios instead ES6 fetch [closed]
A few reasons for using Axios over Fetch:
- Ability to monitor request progress
This is more of a question between XMLHttpRequest (which powers axios) or Fetch API.
Fetch API currently does not provide any way to get notified of the request progress, a feature which powers feedback mechanism for large file uploads for example.
Axios, on the other hand, has this functionality built in:
axios.post('/api', data, {
onUploadProgress: ({ total, loaded }) => {
// update progress
}),
})
- Error handling
When your backend returns 500 Internal Server Error
response code, fetch
will not treat it any different from 200 OK
.
This is an inconvenience in most cases since all your previous assumptions of what a response would look like are no longer valid.
Most often, when receiving an erroneous response from the server you'd want to abort the processing pipeline as soon as possible, and switch to an error handling case.
fetch(url)
.then(reponse => {
if (!(status >= 200 && status < 300)) {
return Promise.reject(new Error("Invalid response status"));
}
return response;
})
.then(response => response.json())
.then(/* normal processing */)
.catch(/* error handling */);
This is not hard to accomplish, but you'd probably want to capture this logic under some abstraction to avoid repetition, and this brings us one step closer to Web API abstraction which is Axios.
Axios does a sane thing and rejects the promise if the response returns erroneous status. This behavior is customizable as are most of the things with axios.
- Testing
Axios has moxios, fetch has fetch-mock.
Both of those libraries are great but in my experience, fetch-mock
required additional setup to get Jest to use mocked fetch over polyfilled one.
I also like that moxios.wait()
returns a promise which will be resolved after matching the request.
- Other features that Axios offers
For example, you can configure an interceptor which will add api key to all request parameters, or monitor active requests to show a loading screen.
Reasons for using one option over the other may vary from actual requirements to convenience.
If you need to monitor progress, use Axios (or XMLHttpRequest).
If you are writing a service worker, use Fetch.
Otherwise, use what's more convenient to you.
This:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title,
body
})
}).then((res) => {
if (res.ok) {
return res.json()
}
throw new Error(res.responseText);
})
.then((data) => console.log(data))
.catch((err) => console.log(err))
can essentially be expressed by axios with this:
axios.post('https://jsonplaceholder.typicode.com/posts', {
title,
body
}).then((data) => console.log(data))
.catch((err) => console.log(err))
So in essence:
- No need to do
res.json()
,res.text()
etc - No need to handle
res.ok
in order to catch non 200 status errors in actual promisecatch
handler. - No need to stringify payload, it's handled by axios by default.
Overall axios
provides a more higher level and simple api to work with requests.